实现系统架构简图如下:
基于Openresty实现的系统架构简图一、编写脚本
1、新建handle_cors.lua脚本文件
ngx.header["Access-Control-Allow-Origin"] ="*"
ngx.header["Access-Control-Allow-Headers"] ="DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range, userid, agent, brandid, language, token"
if ngx.var.request_method =="OPTIONS"then
ngx.header["Access-Control-Max-Age"] ="1728000"
ngx.header["Access-Control-Allow-Methods"] ="GET, POST, OPTIONS, PUT, DELETE"
ngx.header["Content-Length"] ="0"
ngx.header["Content-Type"] ="text/plain, charset=utf-8"
end
二、配置Nginx
1.配置nginx.conf信息
在server里对需要跨域的url添加
location / {
# CORS handle_cors.lua path:"lua/handlefile/handle_cors.lua"
header_filter_by_lua_file lua/handlefile/handle_cors.lua;
if($request_method='OPTIONS') {
return204;
}
proxy_pass http://xxx.xx;
}
参考:https://blog.csdn.net/u010277446/article/details/78654491
踩坑:访问Openresty服务器时,使用postman、curl都是可以调通接口接收到正确响应的,但是在swagger-ui页面中执行execute时,总是返回403,“TypeError: Failed to fetch”!使用如下所示针对nginx的跨域配置是无效的,只有根据上述方法,使用lua脚本设置才起作用。
#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
网友评论