我想从一个网址请求重定向到另一个'POST'请求,如下所示:
var app = require('express')();
app.get('/', function(req, res) {
res.redirect('/test');
});
app.post('/test', function(req, res) {
res.send('/test page');
});
app.listen(3000, function() {
console.log('listenning on port:3000');
});
但是,我无法重定向到'/ test'页面,因为它是一个POST请求。
那么我该怎样做才能使重定向工作,保持'/ test'请求POST?
答案 0 :(得分:29)
你可以这样做:
app.post('/', function(req, res) {
res.redirect(307, '/test');
});
这将保留发送方法。
作为参考,307 http代码规范是:
307临时重定向(自HTTP / 1.1起)在这种情况下,请求 应该使用另一个URI重复,但未来的请求仍然可以使用 原始URI.2与303相比,请求方法不应该 重新发出原始请求时更改。例如,一个POST 必须使用另一个POST请求重复请求。
有关详细信息,请参阅:http://www.alanflavell.org.uk/www/post-redirect.html
答案 1 :(得分:2)
请记住中间件架构:每个处理程序可以操纵上下文,并响应 - 或 - 调用next()
。
通过这个前提,快速路由器基本上是一个中间件功能,你可以在“纠正”网址后使用。
(顺便说一下,请求应用程序也是一个功能,虽然我不确定我是否建议在链中这么早就回去)
这是一个很好的例子:
const router = new require('express').Router()
const user = require('../model/user')
//assume user implements:
// user.byId(id) -> Promise<user>
// user.byMail(email) -> Promise<user>
const reqUser = userPromise => (req, res, next) =>
req.user
? next()
: userPromise(req)
.then(user => { req.user = user })
.then(next, next)
//assume the sever that uses this router has a
//standard (err, req, res, next) handler in the end of the chain...
const byId = reqUser( req => user.byId(req.params.id) )
const byMail = reqUser( req => user.byMail(req.params.mail) )
router.post('/by-id/:id/friends',
byId,
(req, res) => res.render('user-friends', req.user)
)
router.post('/by-email/:email/friends',
byMail,
(req, res, next) => {
req.url = `/by-id/${req.user.id}/friends`
next()
},
router
)
答案 2 :(得分:1)
我认为问题在于节点服务器正在接收POST请求,但需要将其作为GET请求重定向到其他服务器。我最近不得不处理类似的问题。这是我的解决方法:
var proxy = require('express-http-proxy');
app.use('incomin/url', proxy('forwarding:server', {
//The proxyRqDecorator allows us to change a few things including the request type.
proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
proxyReqOpts.method = 'GET';
return proxyReqOpts;
},
//The proxyReqPathResolver takes the Given URL and updates it to the forward path
proxyReqPathResolver: function (req) {
return new Promise( (resolve, reject) => {
setTimeout( () =>{
var value = req.body.key;
var resolvedPathValue = 'forwarding/url' + value;
console.log(`Inside forward path. The resolved path is ${resolvedPathValue}`);
resolve(resolvedPathValue);
}, 200);
});
}
}));
请记住,上面的proxyReqPathResolver是异步设置的。同步描述和更多有关express-http-proxy的信息在这里描述: https://www.npmjs.com/package/express-http-proxy
答案 3 :(得分:0)
307和302之间的唯一区别是307保证在发出重定向请求时,方法和主体不会更改。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307