Node 代理與純靜態服務器ecstatic插件代碼應用整理

第三個代理插件是基於第一個進行擴展。第二個是純靜態服務器插件。

 

// http-proxy code

var port = parseInt(process.argv[2]);

var http = require('http');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});

http.createServer(function (req, res) {
	if (req.url.indexOf('/xxx/abc') === 0) {
	  	proxy.web(req, res, { target: 'http://127.0.0.1:9999' });
	} else {
		app(req, res)
	}
}).listen(port, function () {
	console.log(`Server running on ${port}...`);
});


// ---- ecstatic code

const http = require('http');
const ecstatic = require('ecstatic')({
  root: `${__dirname}`,
  baseDir: '/api',
  showDotfiles: false,
  hidePermissions: true,
  handleError: true,
  handleOptionsMethod: true
});

http.createServer(ecstatic).listen(9999);

console.log('Listening on :9999');


// ----- http-proxy-middleware code

var proxy = require('http-proxy-middleware')

// proxy middleware options
var options = {
  target: 'http://localhost:9999', // target host
  changeOrigin: false, // needed for virtual hosted sites
  // ws: true, // proxy websockets
  pathRewrite: {
    '^/api/old-path': '/api/new-path', // rewrite path
    '^/api': '/' // remove base path
  }
}

// create the proxy (without context)
var exampleProxy = proxy(options)
app.use('/api', exampleProxy)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章