nginx解决跨域方式--JSONP跨域 和 CORS跨域解决
文档说明:只记录关键地方; 发文时间: 2022-10-26
目标:使用CORS 和 jsonp 解决跨域问题
一:nginx 使用CORS解决跨域
涉及到nginx 配置也就这些
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods 'GET,HEAD,POST,PUT,DELETE,CONNECT,OPTIONS,TRACE,PATCH' always;
add_header Access-Control-Allow-Credentials 'true' always;
## 用于自定义请求头参数,或者响应头参数 (未涉及自定义请求头和相应头,不需要此配置),下面是:例子
add_header Access-Control-Allow-Headers "Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,authorization,accept-ranges,content-length,content-type,date,server,last-modified,etag";
# (未涉及自定义请求头和相应头,不需要此配置)
add_header Access-Control-Expose-Headers "Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,authorization,accept-ranges,content-length,content-type,date,server,last-modified,etag";
if ( $request_method = "OPTIONS" ) {
return 204;
}
二:nginx 使用jsonp 解决跨域
location /ip/jsonp {
set $callback "callback";
if ($arg_callback) {
set $callback $arg_callback ;
}
charset utf-8;
default_type application/javascript ;
return 200 '$callback({
"request_time":"$time_local",
"ip":"$remote_addr",
"port":"$remote_port",
"message":"你可真是个小机灵鬼,被你发现了!😁😄😜😋🤗😅😇🥰🥳"
})'
;
}