Nginx 跨域设置 Access-Control-Allow-Origin 无效的解决办法

2018 年 8 月 27 日 0 条评论 10.14k 次阅读 1 人点赞

当出现403跨域错误的时候 No 'Access-Control-Allow-Origin' header is present on the requested resource,需要给Nginx服务器配置响应的header参数

网上大多数的解决方案是:
只需要在Nginx的配置文件中配置以下参数:

location / {  
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
  add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
} 

事实上这个参数在我的 Nginx 1.12 上并不能用。

 

建议用下面的参数:

location /
    {
    	#跨域设置
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        if ($request_method = 'POST') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }
        if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }
        
    }

客户端Ajax 请求示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Ajax 跨域请求</title>
</head>
<body>
<input id="submit" value="submit" type="button">
  
  
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
  
    $(function(){


        $("#submit").on('click',function(){
            var parameters = {orgid:"1101080324323218",appKey:"12dfa63521f952b417bc428ae5dbae3d"}
			
            $.ajax({
                type: "POST",
                async: true,
                url: "https://test.auan.cn/api/getToken.htm",
                data: JSON.stringify(parameters),
                timeout: 5000,
                dataType : "json",
		contentType: 'application/json',
                beforeSend: function () {

                },
                success: function(data){
		    alert("YES");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    alert("NO");
                }
            });
        });


    });
</script>
</body>
</html>

 

雷雷

这个人太懒什么东西都没留下

文章评论(0)

(Spamcheck Enabled)