[英]Configuring CORS with NGINX and AWS Elastic Beanstalk
我的應用程序是 AWS EC2 實例,我遇到了 CORS 錯誤的一些問題。
它在本地服務器上工作得很好,但在生產服務器上卻不行。 我的應用程序是前端的 angular 11 應用程序。 它是 Spring 啟動 API。 它部署在 aws elastic beanstalk 中,我知道 aws 使用 nginx 這就是為我生成 cors 錯誤的原因
然后我嘗試了一個我找到的解決方案:file path.ebextensions\nginx file 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.
spring 中的 CORS 配置:在此處輸入圖像描述
該應用程序在生產中運行良好,除非我使用字段添加大於 1MB 的文件,此時它會生成 CORS 錯誤。
這些都沒有解決問題。 我在這里想念什么?
非常感謝您的幫助!
您應該在 Spring 應用程序中配置 CORS。
創建一個實現 WebMvConfigurer 接口的@Configuration class
覆蓋方法 addCorsMappings(),如下面的示例,它允許所有方法、所有來源並適用於所有 API,又名:全局 CORS 配置。
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}
如果您想選擇性地應用於特定 API,請參閱下面的指南
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.