【发布时间】:2021-08-22 14:38:24
【问题描述】:
我的应用是一个 AWS EC2 实例,我遇到了一些 CORS 错误问题。
它在本地服务器上运行良好,但在生产服务器上却不行。我的应用程序是前端的 Angular 11 应用程序。它是一个 Spring Boot API。它部署在 aws elastic beanstalk 中,我知道 aws 使用 nginx,这就是为我生成 cors 错误的原因
然后我尝试了一个我找到的解决方案:文件路径 .ebextensions\nginx 文件 nginx.conf
user nginx;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_processes auto;
worker_rlimit_nofile 33282;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
include conf.d/*.conf;
map $http_upgrade $connection_upgrade {
default "upgrade";
}
server {
listen 80;
server_name dominio.com;
root /var/app/current/public;
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;
}
}
location /api {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
access_log /var/log/nginx/access.log main;
client_header_timeout 60;
client_max_body_size 10M;
client_body_timeout 60;
keepalive_timeout 60;
gzip off;
gzip_comp_level 4;
# Include the Elastic Beanstalk generated locations
include conf.d/elasticbeanstalk/01_static.conf;
include conf.d/elasticbeanstalk/healthd.conf;
}
}
Nginx 默认有一个配置文件位于 /etc/nginx/nginx.conf 中。这个文件有很多用于所有请求的默认属性,其中之一是 client_max_body_size。该属性的默认值为 1MB。
在文件中,我将 client_max_body_size 更新为 10MB,但是当我发送大于 1 MB 的文件时,cors 错误仍然存在:
Access to XMLHttpRequest at 'https://dominio.com/api' from origin 'https://www.dominio.frontend.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
春天的CORS配置: enter image description here
该应用程序在生产中运行良好,除非我使用字段添加大于 1MB 的文件,此时它会生成 CORS 错误。
这些都没有解决问题。我在这里错过了什么?
非常感谢您的帮助!
【问题讨论】:
标签: amazon-web-services nginx amazon-ec2 cors