启用了CORS模块的请求资源上没有“ Access-Control-Allow-Origin”标头

时间:2019-02-06 16:43:35

标签: express cors

我正在尝试使用Serverless在我的AWS Lambda服务器上使用CORS。现在,我有两个子域(api.site.co和app.site.co)。

在Express上的app.js文件中,我已经安装了CORS并启用了它,例如:

app.use(
  cors({
    origin: 'https://app.site.co',
    optionsSuccessStatus: 200,
  }),
);
app.options('*', cors());

然后在React中使用Axios模块,我会打电话:

axios
   .post('/users/register', user)
   .then(res => history.push('/login'))
   .catch((err) => {
     dispatch({
       type: GET_ERRORS,
       error: err.response.data,
     });
   });

此外,在我的客户端应用程序的app.js文件中:

axios.defaults.baseURL = 'https://api.site.co';

提交任何请求时,我都会收到此错误:

Access to XMLHttpRequest at 'https://api.site.co/users/register' from origin 'https://app.site.co' 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.

到目前为止,我还尝试将CORS配置更改为:

app.use(cors());
app.options('*', cors());

但是我仍然遇到相同的错误。

关于如何解决此问题的任何建议?

2 个答案:

答案 0 :(得分:1)

好像有错字:

https://app.site.co/users/register => https://api.site.co/users/register

您正在向https://api.site.co发送请求,但您的配置指定了https://app.site.co

答案 1 :(得分:0)

这是AWS Lambda Serverless设置的问题。我需要添加

functions:
  app:
    handler: app.handler
    events:
      - http:
          path: /
          method: any
          cors:
            origin: 'https://app.site.co'
      - http:
          path: '{proxy+}'
          method: any
          cors:
            origin: 'https://app.site.co'

以便在代理Express中间件时允许CORS请求。