CORS error when calling post api directly from client - reactjs

I have a post function that I have tested and is working perfectly. When I call it from my front end, I get the following error:
Access to XMLHttpRequest at 'https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried disabling CORS and using different cognito identity pools to allow different permissions, but I still get the same error. When testing it in AWS, it is successful with no errors.
Here is where I am calling the API:
import { API } from "aws-amplify";
export default (async function submitSite(values) {
console.log(values);
return API.post("sites", "/sites", {
body: values
})
});
Here is where I am defining the function in my serverless.yml file:
createSite:
handler: CreateSite.main
events:
- http:
path: sites
method: post
cors: true
authorizer: aws_iam

I'd recommend you to check these.
Make sure you enable CORS in your API gateway as described here
Make sure your server less app have CORS enabled here.
Don't forget adding Access-Control-Allow-Origin response header to your function.
module.exports.hello = function(event, context, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify({ "message": "Hello World!" })
};
callback(null, response);

Related

React.js - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. [AWS - Lambda - API GATEWAY]

I have a react client application that sends form data to AWS API Gateway.
When I test the API with Postman everything works fine, but when I use Axios in react, an error is shown in the console :
Access to XMLHttpRequest at 'https://execute-api.eu-west-3.amazonaws.com' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I enabled CORS in API Gateway methods, also my AWS Lambda function has Lambda proxy integration, but apparently it didn't solve the issue.
How can i fix this ? Thanks in advance.
----- UPDATE -------
Based on the comments, here is the build function for the response I'm sending from the Lambda function :
const buildResponse = (statusCode, body) => {
return {
statusCode : statusCode,
headers : {
"Content-Type" : "application/json",
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
},
body : JSON.stringify(body)
}
}
Where I make the call :
const get = async () => {
const params = {
TableName: dynamoTable
}
const all= await scanDynamoRecords(params, []);
const body = {
data: all
}
return buildResponse(200, body);
}
After reading about CORS and consulting with a professional, response headers must be updated to the following in order to fix the problem :
headers : {
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*"
}
Of course, CORS must be enabled on API Gateway for each method used.
Try to enable credentiels for axios like this:
axios.defaults.withCredentials = true;

POST request to API created by lambda function in amazon AWS in python works good in postman but not in reactjs code

I have written the following code in my react js file, in the place of URL there is my AWS link.
const { empid, name, author } = body;
const onInputChange = e => {
setUser({ ...body, [e.target.name]: e.target.value });
};
const onSubmit = e => {
e.preventDefault();
axios.post(url, body);
history.push("/");
console.log(body);
};
This is my error I have already added Moesif origin crops extension to my browser :
Access to XMLHttpRequest at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Check if the API has CORS disabled
Check if there a trailing / at the end of the api that you are calling. If there a trailing / then remove it. Ex: www.example.com/api/get_lists/ should be www.example.com/api/get_lists
You need to enable cors on your Api Gateway resource.
Also if you are using lambda proxy you need to return cors headers from your lambda response as well.
return {
statusCode: 200,
body: '<response as string>',
headers: {
'Access-Control-Allow-Origin': 'your allowed domains',
... // Other cors headers
}
}
Looks like that the CORS option is not enabled on your API Gateway Resource.
1 - Go to your API Gateway Resource and enable CORS.
2 - Re deploy your API Gateway for the changes to take effect.

ReactJS: access to fetch has been blocked by CORS policy

I am getting the following error in my ReactJS project:
"access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
If an opaque serves your need set the request mode to 'no-cors' to fetch the resource with CORS disabled."
This is how I send requests to the backend:
export const sendRequest = async ( endpoint = '' ,
method = 'GET', body) => {
const response = await fetch(`${url}${endpoint}`, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
const data = await response.json();
return data;
}
I thought first that it is a backend problem but I checked there, found backend CORS Access is enabled for the same headers and client.
Any modifications should I do to the function above??
There an npm module called cors. You can install it in your backend. If you are using ExpressJS, you can just use cors as an middleware using app.use(cors()). With the equivalent header set in the request, it should work

fetching express back-end with react return 405 error (from origin 'null' has been blocked by CORS policy: Response to preflight etc...)

I have a small express/react app. I'm running server side on port 5000 and client side on port 3000. I have the following component on the front-end:
componentDidMount() {
fetch('http://localhost:5000/auth/google',
{
method: 'GET',
headers: {'Content-Type': 'application/json'},
credentials: 'same-origin',
'Access-Control-Allow-Origin': '*'
})
.then(res => {
if (!res.ok) {
throw res;
}
return res.json()
}).then(data => {
this.setState({loading: false, data});
}).catch(err => {
console.error(err);
this.setState({loading: false, error: true});
});
}
on the back-end I have this:
router.get(
"/auth/google",
passport.authenticate("google", { scope: ['Profile','https://www.googleapis.com/auth/analytics.readonly'] })
);
router.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/error", session: false }),
function(req, res) {
var token = req.user.token;
request('https://www.googleapis.com/analytics/v3/management/accounts?access_token=' + token,
function (error, response, body) {
console.log(JSON.parse(body).items);
res.send(JSON.parse(body).items)
});
}
);
and here are the error I have:
Failed to load resource: the server responded with a status of 405 ()
and
Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&scope=Profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&client_id=blablabla.apps.googleusercontent.com' (redirected from 'http://localhost:5000/auth/google') from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
CORS security violation is triggered by your browser which:
has got React code (presumably script bundles) from one server,
is seeing attempts by this code to fetch from another server that is not telling the browser to calm down and tolerate this security violation.
Failed to load resource: the server responded with a status of 405
This means the browser attempted to contact 'another server' prior to fetch and ask if it should tolerate the security violation but 'another server' refused to talk. Technically speaking, the browser has sent HTTP request using HTTP verb OPTIONS and the server responded by indicating it doesn't support this verb.
Access to fetch at 'https://accounts.google.com/o/oauth2/
That's the actual CORS violation detected by the browser which effectively refused to execute fetch.
There are lots of recipes how to calm down the browser so that it would tolerate CORS violations. But the best apprroach is to ensure the violations won't happen so that there is no need to relax the security.
The output of a React application build are .html files and script bundles, possibly source maps. Called build artifacts. If you structure your project so that in both development and production the browser gets everything (build artifacts, API responses) from one single source e.g. Express then there will be no room for CORS issues.

Failed to upload data from heroku app. CORS error

I'm trying to fetch my data from a heroku app into Redux, but I think I'm running into a CORS issue. I've been playing with "headers" for a while and still can't figure it out.
This is the exact error:
"Failed to load https://name-app.herokuapp.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
And this is my code:
export function fetchMicros() {
return dispatch => {
const url = "https://name-app.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' },
})
.then(handleErrors)
.then(res => res.json())
.then(micros => {
dispatch(fetchVitamins(micros));
}
)};
};
If you don't have to do any authentication nor need to pass any data, you can do a no-cors request (more information on mdn page).
fetch(url, {
mode: 'no-cors',
})
If you do need cookies or some kind of authentication, then you need to make the server accept your domain and request methods on the preflight response.
In the event that you don't have access to change that on the server, you can create a nodejs server that will handle the calls for you, bypassing any cors checks (only browser cares about cors, servers don't).

Resources