首页 > 开发 > NodeJS > 正文

使用http-proxy做的代理服务,为什么前端页面的访问的地址必须和请求接口的地址统一

2017-09-08 17:11:19  来源:网友分享

1.使用node模块http-proxy请求代理服务时,能成功代理成功,但是问题是, 浏览器使用localhost:8001/index.html 访问页面,页面中的数据接口地址就必须写成 http://localhost:8001/CpyUser...

如果浏览器写成访问127.0.0.1:8001/index.html访问页面,页面中的数据接口地址就必须写成 http://127.0.0.1:8001/CpyUser...

有没有一种通用的方法:

服务代码如下:

// 新建一个代理 Proxy Server 对象var proxy = httpProxy.createProxyServer({ target: 'http://192.168.1.102:8080/CpyService/bs' });// 捕获异常proxy.on('error', function (err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong. And we are reporting a custom error message.');});var server = require('http').createServer(function(req, res) {     var pathname = url.parse(req.url).pathname;   if(pathname.indexOf("CpyUser") > 0){   console.log('代理服务', req.url, res)  //  req.url = req.url.replace('/mspj-mall-admin', '')  proxy.web(req, res);   // return;} else {  handler (req, res) // 处理静态资源的请求}var host = req.url;host = url.parse(host); host = host.host;console.log("host:" + req.headers.host);console.log("client ip:" + (req.headers['x-forwarded-for'] || req.connection.remoteAddress));});

解决方案

问题解决了,我只要将前端接口写成 var url = 'http://' + window.location.host + '/CpyUser/login' 可以了,无论是通过localhost:8001 访问我的页面还是通过IP访问我的页面,都是能够正常访问接口的。