node.js - 使用 nginx 和 aws 启用 cors 的正确配置是什么?

标签 node.js angular amazon-web-services nginx cors

我正在将我的应用程序迁移到 AWS EC2 实例,它曾经托管在 Hostgator 中并且工作正常,现在我已经成功迁移它,但我遇到了一些 CORS 错误问题。

我的应用程序是前端的 Angular 6 应用程序,我使用 nginx 部署了它。后端托管在 heroku 中,它是 NodeJs 8.0 Restful API

经过许多小时的研究,我发现我必须更改应用程序的服务文件。

一开始是这样的,除了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.

希望你们能给我一些指导

提前致谢

最佳答案

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

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

在 server.js 文件中:-

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

    const corsoption = { 起源:真实, 方法:“获取、头部、放置、补丁、发布、删除”, 凭证:真实, 暴露 header :[“x-auth-token”] };

  • app.use(cors(corsoption));

那么您将不会被 CORS 政策阻止。

文档:- cors package

关于node.js - 使用 nginx 和 aws 启用 cors 的正确配置是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56963725/

相关文章:

css - Angular ngStyle - 绑定(bind)动态和静态 css 属性

powershell - 使用 AWS Powershell 将数据从 Amazon S3 服务器复制到本地驱动器。

ruby - 如何检查实例状态在 ruby​​ 中使用 "aws-sdk"?

node.js - 通过 UDP 和 Node.js 通过 WAN 在两台计算机之间传递 OSC 消息

javascript - 使用 node.js : Error: failed to connect to [localhost:27017] 设置 MongoDB

javascript - Node.js 不等待数据

django - 将敏感环境变量包含到 AWS EB Django 应用程序

node.js - Node + express : Multiple authentication strategies according to page and user type

angular - 对话框测试 - 当我模拟 this.store$.pipe( select(...) ...).subscribe(..) 时,Jasmine 返回 this.store$.pipe 不是函数

javascript - 读取组件文件 Angular 中的响应 header