Express中间件中对request.url的更改是否保留到下一个中​​间件上? [英] Do changes to request.url in Express middleware persist on to the next middleware?

查看:81
本文介绍了Express中间件中对request.url的更改是否保留到下一个中​​间件上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可重写request.url的中间件.但是,在next()中间件中,request.url仍然是原始的未修改的URL.

I have a middleware that rewrites the request.url. However in the next() middleware, the request.url is still the original unmodified url.

示例:

var express = require('express');
var router = express.Router();

router.use(function(req, res, next) {
  console.log('Before Rewrite',req.url);
  if(/^\/v[1-9]/.test(req.originalUrl) ) {
    console.log('Rewritten');
    req.url = '/api' + req.originalUrl;
  }
  console.log('After Rewrite',req.url);
  next();
});
router.use('/api', function(req, res, next) {
  console.log('Next', req.url);
  next();
});

示例网址为'/v3/foo',以下内容将输出到控制台:

With an example url of '/v3/foo' the following is output to console:

Before Rewrite /v3/foo
Rewritten
After Rewrite /api/v3/foo
Next /v3/foo

是否有任何关于为什么请求更改不会持续到下一个中​​间件的想法?

Any thoughts on why the request changes do not persist on to the next middleware?

推荐答案

感谢@kelz到Express next()的链接

Thanks to the link from @kelz to the Express next() code, I have a better understanding of how Express handles urls. It seems that req.url is writeable because Express removes the root of the url when matching. For example with an original url of '/foo/bar', if you have this:

router.use('/foo',someMiddleWare);

router.use('/foo', someMiddleWare);

然后someMiddleWare中的req.url现在将是'/bar',即删除匹配的根.这就是为什么我们需要req.originalUrl(不可写)来保留未更改的url.

Then req.url within someMiddleWare will now be '/bar' i.e. with the matched root removed. This is why we have req.originalUrl (which is not writeable) to persist the unaltered url.

由于我原来的重写url的方法行不通,因此我选择了一个更简单的解决方案:

As my original approach to rewriting the url can't work, I opted for a simpler solution:

  router.all(/^\/v[1-9]/, function(req, res) { res.redirect('/api' + req.originalUrl); });

这样,在重定向之后,req.originalUrl就和我以后的中间件一样.

This way, after the redirect, the req.originalUrl is as it should be for my later middleware.

这篇关于Express中间件中对request.url的更改是否保留到下一个中​​间件上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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