我正在将我的 Nodejs 应用程序部署到运行 nginx 的 AWS Elastic Beanstalk。
该应用程序本质上是一个 API,我可以调用它并检索 JSON 数据,即 myapi.awselasticbeanstalk.com/api/get_stuff 等。
我正在尝试启用 CORS,以便我可以从我的 javascript 应用程序(客户端)访问服务器。
根据亚马逊文档,我可以编辑或扩展 nginx 配置,将配置文件添加到 .ebextensions 文件夹。
cors.config
files:
/etc/nginx/conf.d/cors.conf:
mode: "000644"
owner: root
group: root
content: |
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
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,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,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,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
}
但这对我仍然不起作用。
最佳答案
如果您在 node/express 应用程序发出的响应中设置 CORS header ,则无需向 Nginx 配置添加任何内容。
下面是对我有用的配置,也在 Beanstalk 上运行 node.js,以及调用 API 的云端托管客户端应用程序。
根据需要修改:
server.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Credentials', true)
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
next()
})
关于node.js - 在 ElasticBeanstalk 中的 nginx 服务器上启用 cors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48173717/