Serve a specific url using express

2019-08-11 17:31发布

问题:

Having an express application and two routes, how can I serve route /foo when accessing route /bar?

app.get("/foo", (req, res) => res.end("Hello World"));
app.get("/bar", (req, res) => /* ??? */);

I don't want to redirect using res.redirect("/foo") because that will change the url. From what I saw connect-middleware would do this job, but it's too complex for what I need.

I only need to forward the request to the /foo route instead and serve it to the client under the /bar route.

How can I do that such as when I open /bar in the browser, I will get back "Hello World"?

I also don't want a regex solution. I want a function like this: res.serveUrl("/foo").

回答1:

You can write also your own "rewriting" engine. In this example you just rewrite the URL and use next() to reach the desired handler:

var express = require('express');
var app = express();

app.get('/foo', function (req, res, next) {
    req.url = '/bar';
    return next();
});

app.get('/bar', function (req, res) {
    console.dir(req.url);           // /bar
    console.dir(req.originalUrl);   // /foo
    console.dir(req.path);          // /bar
    console.dir(req.route.path);    // /bar
    res.send('Hello bar!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

You can still access the original url using req.originalUrl

Others (express-urlrewrite) already thought of such middleware as well.



回答2:

You can simply create handler function and use it in both routes

function handleFooAndBar (req, res, next) {
    res.send('Hello World!');
}

app.get("/foo", handleFooAndBar); 
app.get("/bar", handleFooAndBar);