背景
我在本地启动生产环境项目的时候,出现了本地域名(127.0.0.1)内有生产环境(xxxx.xxx.com)的cookie ,但是在想生产环境发送请求的时候,没有带上cookie,后端针对这种情况会报错,影响了测试。
解决方法
启动本地服务:
sudo npm install -g http-server
// 项目根目录 含有dist文件夹
// 启动本地服务
http-server ./dist/ -p 5000
将生产环境域名定向到本地
sudo vim /etc/hosts
// 新增一行 xxxxx.xxx.com 是请求后端的域名
127.0.0.1 xxxx.xxx.com
// 重启网络生效
sudo /etc/init.d/networking restart
node服务监听80端口转发
安装http-proxy依赖
npm install http-proxy
var http = require('http'), httpProxy = require('http-proxy');
// 新建一个代理 Proxy Server 对象
var proxy = httpProxy.createProxyServer({});
// 捕获异常
proxy.on('error', function (err, req, res) {
console.log(err)
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
// 在每次请求中,调用 proxy.web(req, res config) 方法进行请求分发
var server = http.createServer(function (req, res) {
// 在这里可以自定义你的路由分发
var path = req.url; F
proxy.web(req, res, { target: path.indexOf('/api/') === -1 ? 'http://localhost:5000' : 'http://39.98.143.18' })
});
console.log("listening on port 80")
server.listen(80);
启动服务
sudo node ./index.js