美文网首页java专题
ajax完美解决跨域问题(jsonp、nginx反向代理)

ajax完美解决跨域问题(jsonp、nginx反向代理)

作者: H_Man | 来源:发表于2017-04-01 13:35 被阅读431次

做过web前端人都知道,经常会有ajax跨域问题,下面列举我经常使用的解决办法
第一种:使用jsonp,jQuery的ajax方法支持jsonp,但是最大的缺点就是只支持get方式,而且服务端也要修改
客户端 test.html代码

<!DOCTYPE html>  
<html>  
<head>  
    <title>工作端</title>  
    <meta name="viewport" content="width=device-width,initial-scale=1.0">  
    <meta charset="utf-8">  
    <script src="jquery-1.10.2.min.js"></script>  
    <style>  
    </style>  
</head>  
  
<body>  
<input type="button" value="测试" id="demo">  
<div id="result">  
  
</div>  
<script>  
$(document).ready(function() {  
    var cache = {};  
    $("#demo").click(function(){  
        $.ajax({  
            type : "get",   
            async:false,  
            data:{"name":"test001","age":"100"},  
            url : "http://192.168.10.111/server.php", //跨域请求的URL  
            dataType : "jsonp",  
            //传递给请求处理程序,用以获得jsonp回调函数名的参数名(默认为:callback)  
            jsonp: "callback",  
            //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名  
            jsonpCallback:"success_jsonpCallback",  
                //成功获取跨域服务器上的json数据后,会动态执行这个callback函数  
            success : function(json){   
                alert(json,name);  
            }  
        });  
    });  
})  
</script>  
</body>  
</html>  

第二种:nginx反向代理,我的nginx版本nginx-1.10.0
首先在 conf\apiserver-reverse-proxy-conf\bingli\main.conf ,没有相关目录和文件就新

location ~* ^/uc/.*{  
    proxy_set_header Host $host;  
    proxy_set_header X-Real-Ip $remote_addr;  
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
    proxy_pass http://192.168.10.111:8080;  
}

然后在nginx主配置文件添加加粗内容,即把代理文件加载进来

location / {  
            root   html;  
            index  index.html index.htm;  
        }  
include apiserver-reverse-proxy-conf/bingli/main.conf;  

重启nginx,之后ajax发请求到
http://localhost/uc/aa
http://localhost/uc/bb?token=xxxx
都会被转发到
http://192.168.10.111:8080/uc/aa
http://192.168.10.111:8080/uc/bb?token=xxxx

相关文章

网友评论

    本文标题:ajax完美解决跨域问题(jsonp、nginx反向代理)

    本文链接:https://www.haomeiwen.com/subject/kseiottx.html