使用Openresty时配置解决跨域问题

实现系统架构简图如下:

基于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;

    }

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容