1. 程式人生 > >nginx 反向代理解決ajax跨域問題

nginx 反向代理解決ajax跨域問題

utf-8 base64 char lac meta god hold time -s

~~寫了段ajax 去請求接口數據的js ,無奈發現有跨域問題。

技術分享

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>index</title>

</head>
<body>
<a id=‘ajax‘>ajax</a>
</body>
</html>

<script src="jquery-v1.10.2.js"type="text/javascript"></script>
<script type="text/javascript" >
$("#ajax").click(function(){
$.ajax({
async: false,
type: "GET",
dataType: ‘json‘,

url: "http://139.196.178.104/ops/v1.0/stuff",
data: "",
timeout: 3000,
contentType: "application/json;utf-8",
success: function(msg) {
console.log(msg);
}
});
});
</script>

利用nginx反向代理

1.創建虛擬域名

在ajax.conf 中加一個location

location ^~/api/{
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://139.196.178.104/;
}

nginx -s reload

這樣 訪問 http://local.ajaxdemo.com/api/ops/v1.0/stuff 地址 和訪問 http://139.196.178.104/ops/v1.0/stuff 得到的數據效果是一樣 的說明 nginx 反向代理配置成功

然後修改ajax

$("#ajax").click(function(){
$.ajax({
async: false,
type: "GET",
dataType: ‘json‘,

url: "api/ops/v1.0/stuff",
data: "",
timeout: 3000,
contentType: "application/json;utf-8",
success: function(msg) {
alert(msg);
console.log(msg);
}
});
});

便可實現抓取接口 http://139.196.178.104/ops/v1.0/stuff的數據

nginx 反向代理解決ajax跨域問題