前端nginx实现跨域请求

前端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/ 这个路径下的请求才进行转发,其他请求是不进行转发的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值