直接進(jìn)入正題:
1.下載http-proxy
cnpm install http-proxy --save-dev
2.在項(xiàng)目下面新建一個(gè)app.js文件,內(nèi)容如下:
varhttp =require('http'), httpProxy =require('http-proxy');// 新建一個(gè)代理 Proxy Server 對(duì)象? varproxy = httpProxy.createProxyServer({});// 捕獲異常? 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.');? });// 在每次請(qǐng)求中,調(diào)用 proxy.web(req, res config) 方法進(jìn)行請(qǐng)求分發(fā)? varserver =http.createServer(function(req, res){// 在這里可以自定義你的路由分發(fā)? varhost = req.headers.hostswitch(host){case'www.veblen.com':? ? ? ? ? ? ? ? proxy.web(req, res, {target:'http://localhost:3000'});break;case'boy.veblen.com':? ? ? ? ? ? ? proxy.web(req, res, {target:'http://localhost:9527'});break;default:? ? ? ? ? ? ? res.writeHead(200, {'Content-Type':'text/plain'});? ? ? ? ? ? res.end('Welcome to my server!');? ? ? ? }? });console.log("listening on port 80")? server.listen(80);
縮進(jìn)敲的夠直觀了,且行且珍惜!
作者:vitor
鏈接:http://www.itdecent.cn/p/adec98717ef2
來(lái)源:簡(jiǎn)書(shū)
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。