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

偶尔善良 提交于 2019-12-11 08:57:51

问题


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?


回答1:


Cors issue

Known issue using localhost to make your call.

The issue during function invocation

The issue is caused by your header values. All values should be strings. The response in the callback expects these values to be strings.

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


来源:https://stackoverflow.com/questions/54096057/netlify-nodejs-function-always-returns-response-to-preflight-request-doesnt-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!