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?