简体   繁体   English

使用express服务特定网址

[英]Serve a specific url using express

Having an express application and two routes, how can I serve route /foo when accessing route /bar ? 有一个express应用程序和两个路由,访问route /bar时如何服务route /foo

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. 我不想使用res.redirect("/foo")进行重定向,因为这将更改URL。 From what I saw connect-middleware would do this job, but it's too complex for what I need. 从我看到的connect-middleware可以完成这项工作,但是对于我所需要的来说太复杂了。

I only need to forward the request to the /foo route instead and serve it to the client under the /bar route. 我只需要将请求转发到/foo路由,然后将其提供给/bar路由下的客户端即可。

How can I do that such as when I open /bar in the browser, I will get back "Hello World" ? 我该怎么做,例如在浏览器中打开/bar时,将返回"Hello World"

I also don't want a regex solution. 我也不需要正则表达式解决方案。 I want a function like this: res.serveUrl("/foo") . 我想要一个这样的函数: res.serveUrl("/foo")

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);

You can write also your own "rewriting" engine. 您也可以编写自己的“重写”引擎。 In this example you just rewrite the URL and use next() to reach the desired handler: 在此示例中,您只需重写URL并使用next()即可到达所需的处理程序:

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 您仍然可以使用req.originalUrl访问原始网址

Others ( express-urlrewrite ) already thought of such middleware as well. 其他人( express-urlrewrite )也已经想到了这种中间件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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