使用快递服务特定网址 [英] Serve a specific url using express

查看:110
本文介绍了使用快递服务特定网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有快递应用程序和两条路线,如何在访问路线<$ c时提供路线 / foo $ c> / bar ?

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) => /* ??? */);

我不想使用 res.redirect(/ foo重定向)因为这会改变网址。从我看到的 connect-middleware 将做这个工作,但它太复杂了我所需要的。

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.

我只需要将请求转发到 / foo 改为路线并在 / bar 路线下将其提供给客户。

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

我怎么能这样做当我在浏览器中打开 / bar 时,我会回来Hello World

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

我也不想要正则表达式解决方案。我想要一个这样的函数: res.serveUrl(/ foo)

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

推荐答案

您也可以编写自己的重写引擎。在此示例中,您只需重写URL并使用 next()即可到达所需的处理程序:

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!');
});

您仍然可以使用 req.originalUrl

其他( express-urlrewrite )已经考虑过这样的中间件。

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

这篇关于使用快递服务特定网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆