使用Openresty時配置解決跨域問題

實(shí)現(xiàn)系統(tǒng)架構(gòu)簡圖如下:

基于Openresty實(shí)現(xiàn)的系統(tǒng)架構(gòu)簡圖

一、編寫腳本

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服務(wù)器時,使用postman、curl都是可以調(diào)通接口接收到正確響應(yīng)的,但是在swagger-ui頁面中執(zhí)行execute時,總是返回403,“TypeError: Failed to fetch”!使用如下所示針對nginx的跨域配置是無效的,只有根據(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;

? ? }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容