Netlify NodeJS函数始终返回“对预检请求的响应未通过”

时间:2019-01-08 16:38:35

标签: node.js lambda cors aws-lambda netlify

我正在尝试使用 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.

enter image description here

我正在尝试在我的代码中处理OPTIONSPOST,但似乎没有用。这是我的代码:

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应用中调用它,如下所示:

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

enter image description here

什么原因导致该错误以及如何解决?

1 个答案:

答案 0 :(得分:3)

Cors问题

Known issue using localhost拨打电话。

函数调用期间的问题

此问题是由您的标头值引起的。所有值应为字符串。回调中的响应期望这些值是字符串。

  

错误解码lambda响应:json:无法将数字解组为字符串类型的Go值

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',
};