【详解】Nginx解决跨域问题

3289 2019-04-22 Nginx

在浏览器中同源策略是一种安全机制,它限制了来自不同源(域名,协议,端口)的“document”如何交互。 当一个域的脚本试图访问领一个域的资源时,会引发跨域错误。这种限制可能导致在开发单页面应用(SPA)或使用第三方API 时遇到问题。

配置跨域

location / {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 3600;
        if ($request_method = 'OPTIONS') {
            # OPTIONS 请求直接返回 200
            add_header 'Access-control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset-utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
}