實(shí)現(xiàn)系統(tǒng)架構(gòu)簡(jiǎn)圖如下:
一碴里、編寫(xiě)腳本
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里對(duì)需要跨域的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
踩坑:訪問(wèn)Openresty服務(wù)器時(shí)靶瘸,使用postman寝优、curl都是可以調(diào)通接口接收到正確響應(yīng)的条舔,但是在swagger-ui頁(yè)面中執(zhí)行execute時(shí),總是返回403乏矾,“TypeError: Failed to fetch”孟抗!使用如下所示針對(duì)nginx的跨域配置是無(wú)效的,只有根據(jù)上述方法钻心,使用lua腳本設(shè)置才起作用凄硼。
#
# 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;
? ? }
}