- Mais recentes
- Mais votos
- Mais comentários
Not sure whether this will help anyone that has a similar issue because the solution to my specific situation lies in the implementation of the axios library to request API calls, and is not related to any AWS configuration in particular.
The Culprit
In my React app, I have a class "BaseController" that handles all my API calls. In the class's constructor I read the backend's base API URL from the ".env" file and stores it in a constant field. When the API request is made, I take the endpoint of the API (e.g. "/login") and append it to the base URL and then pass the result through to axios.
import axios from "axios";
const BASE_URL = process.env.REACT_APP_BASE_URL;
export default class BaseController {
constructor() {
this.BASE_URL = BASE_URL;
}
sendRequest = async (method, url, body) => {
let config = {
method: method
};
url = `${this.BASE_URL}/${url}`;
// Remove any duplicate '/'
url = url.replace(/\/+/g, "/");
if (params) {
config.params = this.addQueryParameters(url, params);
}
if (body !== null) {
config.data = JSON.stringify(body);
}
const response = await axios(url, config);
return response.data;
};
}
However, the URL passed through to axios is not read as the absolute URL that it should use. So, when the request is made from the CloudFront domain, axios uses the CF domain as its base URL. Why this is not happening on my local machine during development, or even in a statically hosted S3 bucket domain, I have no idea.
The solution
Properly set the default base URL for axios, like so:
axios.defaults.baseURL = baseURL;
So the above function would then look like this:
import axios from "axios";
const BASE_URL = process.env.REACT_APP_BASE_URL;
export default class BaseController {
constructor() {
axios.defaults.baseURL = BASE_URL;
}
sendRequest = async (method, url, body) => {
let config = {
method: method
};
// Remove any duplicate '/'
url = url.replace(/\/+/g, "/");
if (params) {
config.params = this.addQueryParameters(url, params);
}
if (body !== null) {
config.data = JSON.stringify(body);
}
const response = await axios(url, config);
return response.data;
};
}
And then it would be used like so (very simplified usage example):
import BaseController from "./BaseController";
const response = await BaseController.sendRequest("POST", "/login", credentials);
Hope this helps someone!
Your endpoint appears to run successfully, but you cannot make POST login requests. You most likely forgot to enable the POST method.
Conteúdo relevante
- AWS OFICIALAtualizada há 2 anos
- AWS OFICIALAtualizada há 2 anos
- AWS OFICIALAtualizada há 2 anos
Thanks for your response! I updated the CF distribution's behavior setting to allow all the HTTP methods, but the issue persists