如何在nginx和aws上启用cors的正确配置?

3

我正在将我的应用迁移到AWS EC2实例上,之前它是托管在Hostgator上,并且一切都运行良好,但现在我已经成功地将其迁移,却遇到了CORS错误的问题。

我的应用程序是一个使用Angular 6构建的前端应用,我使用nginx进行部署。后端托管在Heroku上,是一个NodeJs 8.0的Restful API。

经过多次研究,我发现我需要更改我的应用程序的serve文件。

一开始它是这样的,除了CORS错误之外,一切都正常运行:

server {     
 listen 80;      
 listen [::]:80;      
 server_name http://your-site-name.com;      
 root /var/www/app-name;   
 server_tokens off;   
 index index.html index.htm;     

 location / {         
     # First attempt to server request as file, then         
     # as directory, then fall back to displaying a 404.          
     try_files $uri $uri/ /index.html =404;      
 }
}

然后我尝试了一个我发现的解决方案

location / {
  if ($request_method = 'OPTIONS') {
     add_header 'Access-Control-Allow-Origin' '*';
     add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

     add_header 'Access-Control-Max-Age' 1728000;
     add_header 'Content-Type' 'text/plain; charset=utf-8';
     add_header 'Content-Length' 0;
     return 204;
  }
  if ($request_method = 'POST') {
     add_header 'Access-Control-Allow-Origin' '*';
     add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
     add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
     add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 }
  if ($request_method = 'GET') {
     add_header 'Access-Control-Allow-Origin' '*';
     add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
     add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
     add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
  }
}

这个方法不起作用,重新加载页面后我收到了一个404未找到nginx错误。下一个解决方案也是同样的情况:

location / {

 # Simple requests
 if ($request_method ~* "(GET|POST)") {
   add_header "Access-Control-Allow-Origin"  *;
 }

 # Preflighted requests
 if ($request_method = OPTIONS ) {
   add_header "Access-Control-Allow-Origin"  *;
   add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
   add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
   return 200;
 }

....
# Handle request
....

最后我尝试了这个:

 location / {
     dav_methods PUT DELETE MKCOL COPY MOVE;

   # Preflighted requestis
   if ($request_method = OPTIONS) {
     add_header "Access-Control-Allow-Origin" *;
     add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD, DELETE";
     add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    return 200;
  }

  # CORS WHITELIST EVERYTHING
  # This is allowing everything because I am running
  # locally so there should be no security issues.
  if ($request_method = (GET|POST|OPTIONS|HEAD|DELETE)) {
    add_header "Access-Control-Allow-Origin" *;
    add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
  }

   try_files $uri $uri/ /index.html$is_args$args;
}

这个最后的解决方案运行良好(即我的应用程序正在加载,且没有出现404错误),但仍然给了我CORS错误。
是的,我在后端启用了CORS,这是我的server.js文件:
require('./config/config.js');

//Requires
const express = require('express')
const colors = require('colors')

const bodyParser = require('body-parser')


const app = express();

//Enable cors
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
Content-Type, Accept, token");
   res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
 next();
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


app.use(require("./routes/index"));


//serve
app.listen(process.env.PORT, () => {
    console.log(`Listening ${process.env.PORT}. Status:`, 'online'.green)
});

这是我在浏览器控制台中遇到的错误

Access to XMLHttpRequest at 
'https://backend.herokuapp.com/inventory/most_sold' from origin 
'http://front-end-ip' has been blocked by CORS policy: No 'Access-Control- 
Allow-Origin' header is present on the requested resource.

我希望有些人能给我一点指导。

提前感谢。

2个回答

0

您可以使用CORS(一个用于提供Connect/Express中间件的node.js包,可用于启用各种选项的CORS)。

  • 通过npm i cors在node.js中安装CORS

在server.js文件中:

  • const cors = require("cors");
  • 然后设置CORS选项,

    const corsoption = { origin: true, methods: "GET,HEAD,PUT,PATCH,POST,DELETE", credentials: true, exposedHeaders: ["x-auth-token"] };

  • app.use(cors(corsoption));

然后您将不会被CORS策略阻止。

文档:cors package


谢谢您的回复,不幸的是这个解决方案并没有起作用。正如我告诉您的那样,在Hostgator上时后端工作得很好,没有跨域错误。这就是为什么我认为它与nginx服务器文件有关。顺便说一下,错误仍然是相同的。 - HanselDoullery
你在 server.js 文件中进行了更改并重新将后端部署到 Heroku 上了吗?! - Abhinav Kinagi
是的,我做了,而且我为了确保做对了,还做了两遍。 - HanselDoullery

0

我在nginx.conf中使用more_set_headers比使用add_header更成功:

    more_set_headers 'Access-Control-Allow-Origin:http://www.mydomain.test';
    more_set_headers 'Access-Control-Allow-Methods: POST';

即使没有Access-Control-Allow-Methods头,这也可以在FF和Chromium上工作。

more_set_headers指令是HttpHeadersMore模块的一部分,该模块包含在nginx的nginx-extras flavor中,您可以使用以下命令在ubuntu 16上安装它:

sudo apt-get install nginx-extras


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接