简体   繁体   中英

Proxy with Express.js + Request.js

I started writing a proxy server with Express.js and Request.js

The server runs on port 900 and does:

  1. Serve static content from path /prototype
  2. For certain calls forward the request to another server (on port 8080)
  3. Resolves /prototype/[this|that] to the corresponding static html /prototype/this.html and /prototype/that.html .
  4. Also serve this.html as default for /prototype

I managed to achieve 1) - 3) with following code:

var express = require('express'), path = require('path'), request = require('request');

var app = express();

app.get('/prototype', function(req, res, next) {
  // a) request(req.protocol + '://' + req.get('host') + req.url +  '/this').pipe(res);
  // b) res.redirect('/prototype/this');
});

app.get('/prototype/:path(this|that)', function(req, res, next) {
  var resolvedUrl = req.protocol + '://' + req.get('host') + req._parsedUrl.pathname + '.html';
  request(resolvedUrl).pipe(res);
});

app.get('/prototype/sample/:path', function(req, res, next) {
  var resolvedUrl = 'http://localhost:8080' + req.url;
  request(resolvedUrl).pipe(res);
});

app
  .use('/prototype', express.static(path.resolve(__dirname, '../')))
  .use(app.router)
  .use(express.errorHandler({
    dumpException: true,
    showStack: true
  }));

module.exports = app;

My folder structure is

prototype
|_css
| |_<css files>
|_js
| |_<js files>
|_this.html
|_that.html

this.html refers to the files in css and in js

<link rel="stylesheet" href="css/app.css" />
<script data-main="js/app.js" src="js/require.js"></script>

In order to achieve 4) I tried to request the /prototype/this path when /prototype is requested, however then the js and css are requested from /js/app.js and /css/app.css instead of /prototype/js/app.js and /prototype/css/app.css which fails. (See a) in the code comment). The behavior I would like to achieve can be achieved with b) but I don't want to have the URL bar in the browser changed to /prototype/this but keep it in /protoype .

Any nice way to do this?

Turned out to be a missing trailing slash.. after /prototype . Without the trailing slash I was overriding the behaviour that redirected to the directory with trailing slash when requesting directory path without trailing slash.

Changed it to the following and it works like a charm.

app.get('/prototype/', function(req, res, next) {
  // a) request(req.protocol + '://' + req.get('host') + req.url +  '/this').pipe(res);
  // b) res.redirect('/prototype/this');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM