我正在尝试使用创建一个 API 端点Netlify Lambda 函数。该代码在我的本地运行完美,但总是返回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.
我正在尝试处理OPTIONS
and POST
在我的代码中,但它似乎不起作用。这是我的代码:
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;
}
};
我试图从 React 应用程序中调用它,使用axios
像这样:
axios.post('https://<my-netlify-project>.netlify.com/.netlify/functions/test', reqObj)
我注意到这个错误出现在我的函数调用中
10:24:58 PM: error decoding lambda response: json: cannot unmarshal number into Go value of type string
导致错误的原因是什么以及如何解决?