close

目的

使存取localhost:5000/app/app1 轉到localhost:3000

使存取localhost:5000/app/app2 轉到localhost:3001

這樣...

var express = require('express');
var app = express();
var http = require('http'),
    httpProxy = require('http-proxy');

app.set('port', process.env.PORT || 5000);

var proxy = httpProxy.createProxyServer();

app.all('/app1/*', function(req, res, next){
    console.log(req.url);
    req.url = req.url.slice(5);
    proxy.web(req, res, {
        target: 'http://127.0.0.1:3000'
    }, function(e) {
        console.log(e);
    }); 
});

app.all('/app2/*', function(req, res, next){
    console.log(req.url);
    req.url = req.url.slice(5);
    proxy.web(req, res, {
        target: 'http://127.0.0.1:3001'
    }, function(e) {
        console.log(e);
    }); 
});

http.createServer(app).listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

使用這段Code,可以將存取

localhost:5000/app1/ 的動作轉到localhost:3000/

localhost:5000/app2/ 的動作轉到localhost:3001/

這裡要注意的是app1中所有的html以及js都必須使用相對url位置存取

比如,在node.js 中的app.js

不可以用res.redirect('/index.html');
要用res.redirect('index.html');

比如,網頁的Javascript

不可以用
         $.ajax({
                 url: '/musicbox',
要用
         $.ajax({
                 url: 'musicbox',

使用相對位置,則使用reverse proxy就不會因為位置不對而無法存取。

arrow
arrow
    文章標籤
    node.js
    全站熱搜

    Perry Wu 發表在 痞客邦 留言(0) 人氣()