Skip to main content

访问 http/https 映射出现CORS跨域异常

在前后端分离的Web服务架构中,前端通过nginx 反向代理,然后利用 ZeroNews 代理到公网,服务端默认是不允许跨域转发的,由于没有配置 nginx 的 CORS跨域,导致后端转发出现CORS异常

** 异常现象 **

解决方法

在 nginx 的代理配置中增加 CORS 配置到后端服务的 location 中,参考如下:

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET, PUT, POST, DELETE, PATCH, OPTIONS;
add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range;

示列:

server {
listen 80;
server_name corssingle.linuxds.com;
location /api {
# CORS 配置
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET, PUT, POST, DELETE, PATCH, OPTIONS;
add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range;
}
}