I'm trying to create an API endpoint using Netlify Lambda Function. The code works perfectly in my local, but always returns Access to XMLHttpRequest at 'https://<my-netlify-project>.netlify.com/.netlify/functions/submit' 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.
I'm trying to handle OPTIONS
and POST
in my code, but it doesn't seems working. Here is my code:
const axios = require('axios');
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*',
'Access-Control-Max-Age': 2592000,
'Access-Control-Allow-Credentials': true,
};
exports.handler = (event, context, callback) => {
if (event.httpMethod === 'OPTIONS') {
callback(null, { statusCode: '204', headers });
return;
}
if (event.httpMethod === 'POST') {
callback(null, {
statusCode: 200,
body: JSON.stringify({
success: true,
}),
headers,
});
return;
}
};
And I'm trying to call it from a React app, using axios
like this:
axios.post('https://<my-netlify-project>.netlify.com/.netlify/functions/test', reqObj)
And I noticed this error appears on my function invocation
10:24:58 PM: error decoding lambda response: json: cannot unmarshal number into Go value of type string
What causes the error and how to resolve it?
Cors issue
Known issue using localhost to make your call.
The issue during function invocation
The issue is caused by your header values. All values should be strings. The response in the callback expects these values to be strings.