直接上nginx配置:
location /api/ {
proxy_set_header Access-Control-Allow-Origin *;
proxy_set_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
proxy_set_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
return 204;
}
proxy_pass http://127.0.0.1:8001/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 500m;
client_body_buffer_size 512k;
proxy_connect_timeout 30;
proxy_send_timeout 3000;
proxy_read_timeout 3000;
proxy_buffer_size 8k;
proxy_buffers 8 128k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
}
网上部分文章将proxy_set_header写成了add_header会导致允许跨域配置不生效,注意proxy_set_header和add_header区别:
proxy_set_header是nginx在收到浏览器发来的请求基础上,添加请求头给到目标服务,add_header是nginx设置响应头信息给浏览器;