Netlify NodeJS Function always returns 'Response to preflight request doesn't pass'

Netlify NodeJS Function always returns 'Response to preflight request doesn't pass'

我正在尝试使用 Netlify Lambda 函数 创建一个 API 端点。该代码在我的本地完美运行,但始终 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.

我试图在我的代码中处理 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;
      }
};

我正在尝试从 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

导致错误的原因以及如何解决?

Cors 问题

Known issue using localhost 拨打电话。

函数调用过程中的问题

问题是由您的 header 值引起的。所有值都应该是字符串。回调中的响应期望这些值是字符串。

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