Nginx 解决前端 CORS 跨域问题

Nginx 跨域 反向代理 About 841 words

问题描述

Access to XMLHttpRequest at 'http://localhost:8080/test' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

前端AjaxAxiosXMLHttpRequest请求一个第三方的接口时,会出现跨域问题。

解决方案

只需在Nginx侧过滤掉OPTIONS请求,不转发给第三方接口,直接在Nginx就返回前端。前端就会认为OPTIONS请求成功了继续发送POST请求,此时Nginx将此次的POST请求真正转发给第三方接口。

配置文件

location /test {
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin $http_origin; # 必须要有
        add_header Access-Control-Allow-Headers *; # 必须要有
        #add_header Access-Control-Allow-Methods GET,POST,OPTIONS; # 不加也行
        #add_header Access-Control-Allow-Credentials true; # 不加也行
        return 200; # 204也可以,只要返回成功码即可
    }
    proxy_pass  http://abc.com/def;
}
Views: 10,427 · Posted: 2020-02-15

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh