Netlify NodeJS函数始终返回“对预检请求的响应未通过" [英] Netlify NodeJS Function always returns 'Response to preflight request doesn't pass'
问题描述
我正在尝试使用 Netlify Lambda函数创建一个API端点.该代码在我的本地环境中运行良好,但始终返回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 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.
我正在尝试在我的代码中处理OPTIONS
和POST
,但是似乎没有用.这是我的代码:
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;
}
};
我正在尝试使用axios
这样从React应用程序中调用它:
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问题
使用本地主机的已知问题拨打电话.
此问题是由您的标头值引起的.所有值应为字符串.回调中的响应期望这些值是字符串.
The issue is caused by your header values. All values should be strings. The response in the callback expects these values to be strings.
错误解码lambda响应:json:无法将数字解组为字符串类型的Go值
error decoding lambda response: json: cannot unmarshal number into Go value of type string
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',
};
这篇关于Netlify NodeJS函数始终返回“对预检请求的响应未通过"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!