CORS策略已阻止“ Access-Control-Allow-Origin”标头

时间:2019-03-20 04:05:38

标签: reactjs api express axios

我创建API,后端和前端网站。

我使用Express for API,后端-使用ReactJs的前端

所以在我当地,一切正常。但是当我部署到服务器时,显示此错误消息

Access to XMLHttpRequest at 'http://domain/headline' from origin 'http://domain' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

Access to XMLHttpRequest at 'http://domain/marketData/snack' from origin 'http://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在ReactJs im中,使用axios来获取数据。

在我的nginx服务器中,我已经设置了

location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:3001;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
        if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' 'http://domain';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
            }
    }

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

首先通过npm i cors在您的api服务器中从 npm 安装 cors 。 然后在您的app.js或server.js或index.js(您创建http服务的主文件)中使用以下代码行

const cors = require('cors');
app.use(cors());
app.options('*', cors());