node.js - Express - 如何修改请求然后重定向到另一条路线?

标签 node.js redirect express request middleware

我正在寻找一种方法来修改我的请求,然后再重定向到我的express.js应用程序中的另一个路由。

我尝试了两种方法来做到这一点:
1)

 #users.coffee
 router.use '/:id', (req, res, next) ->
   req.currentUser = req.params.id
   req.url = '/'
   next()

 #app.coffee
 app.use '/users', require('./routes/users')
 app.get '/', (req, res) ->
   locals = {}
   if req.currentUser
     locals.currentUser = req.currentUser
   res.render 'index', locals

2)

 #users.coffee
 router.use '/:id', (req, res, next) ->
   req.currentUser = req.params.id
   res.redirect '/'

 #app.coffee
 app.use '/users', require('./routes/users')
 app.get '/', (req, res) ->
   locals = {}
   if req.currentUser
     locals.currentUser = req.currentUser
   res.render 'index', locals

使用第一种方法时,不会发生重定向,使用第二种方法时,不会呈现页面。

最佳答案

我想要实现的目标可能是不可能的。客户端请求发送的url无法修改。我只能发送状态 302 和重定向 url,然后客户端发出新的 get 请求。所以有两个不同的请求。
不过我可以在查询中改变url的斜杠格式。

#users.coffee
 router.get '/:id', (req, res) ->
   res.redirect '/?user:'+req.params.id

关于node.js - Express - 如何修改请求然后重定向到另一条路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28070705/

相关文章:

javascript - 如何在 Node.js 的 console.log() 中创建换行符

node.js - 使用 NodeJs Express 在 JavaScript 上推送通知

java - 使用 Apache Server 为在 Tomcat 中运行的网站设置重定向

javascript - NodeJs sendFile 没有加载 webpack 包

node.js - 将 KrakenD 与本地 Nodejs 服务器结合使用

node.js - Grunt --force 失败, Node 为 : bad option

apache - htaccess 将 mydomain.com/knowledgebase.php 更改为 mydomain.com

linux - Iptables 或在网关中重定向 IP 的东西 (GNU/Linux)

node.js - promise 重发

node.js - 将请求从静态包代理到 Express 后端时,NginX 无法传递 POST 请求正文