前端nginx实现跨域请求
nginx是一个代理服务器,他会把你的请求分发到目标服务器,然后把图文资源在返回给你的浏览器
如何在自己电脑安装nginx,实现前端跨域请求
前端代码如下
//ajax请求公用函数
function ZPost(handlerUrl, sendData, successFun, errorFun){
var apiHost="/proxy/html";
//nginx配置的location ^~/proxy/html/ ,也就是只转发这个地址开头的请求
$.ajax({
url: apiHost + handlerUrl,
type: "POST",
async:true,
xhrFields:{withCredentials:true},
dataType :"json",
data: sendData,
success: function(result) {
successFun(result);
},
error: function(result) {
console.log(result);
}
});
}
ZPost("/category/findall", null, function (res) {
console.log(res,999)
})
nginx配置文件如下修改
server {
#8888是访问nginx的端口
listen 8888;
server_name 127.0.0.1;
location / {
root html;
index index.html index.htm;
}
location ^~/proxy/html/{
rewrite ^/proxy/html/(.*)$ /$1 break;
#proxy_pass 是远程服务器的地址
proxy_pass http://localhost:8666/;
}
}
说明:
启动nginx服务器后打开
http://127.0.0.1:8888/proxyTest/index.html
打开这个网址,就没有跨域问题了
这里访问的是nginx服务器下的文件,Hbuilder打开文件后,不能用Hbuilder的内置服务器,要访问nginx的地址
location ^~/proxy/html/
是指只有 http://127.0.0.1:8888/proxy/html/ 这个路径下的请求才进行转发,其他请求是不进行转发的