我对 express 和 request-promise 模块比较陌生,需要创建一个从 serverA 调用的服务 S,在 S 向 ServerB 询问一些附加信息后,它将 serverA 的请求重定向到 ServerC。由于我收到错误:发送后无法设置标头。即使我自己没有添加一些东西,我想知道有人可以帮助我完成这个工作流程。
代码如下:`
const express = require('express')
const rp = require('request-promise')
...
app.get('/dispatch', cors(), (req, res, next) => {
var options = {
uri: 'https://ServerB/calc-something..',
headers: {
'User-Agent': 'its-me',
'Data': data_from_serverA
},
resolveWithFullResponse: true, // Get statuscode
json: true // Parse the JSON string in the response
};
rp(options) // Do request to serverB
.then(function (response) {
console.log(`ServerB responded with statuscode ${response.statusCode}`)
// No error, so redirect original res
res.redirect('https://serverC/...') // error occurs here
return next(response)
})
.catch(function (err) {
console.log(`ServerB responded with error ${err}`)
return next(err) // send 500 to serverA
})
})`
发布于 2019-03-01 04:18:24
你的cors()中间件正在设置CORS标头。这会导致在解析promise时发送报头。
重定向也会发送报头,这就是问题所在。重定向设置一个location标题,但你已经发送了标头,所以这将不起作用。
解决方案是将最终的中间件一分为二。首先,检查是否需要重定向,如果需要,就进行重定向。否则,在req对象,并在cors调用之后处理此事件。
您的最终路线将如下所示:
app.get('/dispatch', checkRedirect, cors(), (req, res, next) => { //do something useful, or send your error })
您的checkRedirect函数的内容将与上面的内容非常相似。但是,您不会将数据传递给next()函数。这只是将控制权传递给下一个中间件。取而代之的是,将所需的任何数据放在req对象,并在cors之后在最终的中间件中处理它。如果你所做的只是设置一个500错误,你甚至不需要CORS。
发布于 2019-03-06 16:16:19
根据@Rampant的回答,这就是我是如何做到这一点的。请求-承诺(rp):
function checkPrecondition(req, res, next){
req.precondition = false
rp({ method: 'POST',
...
})
.then((data) => {
...
req.precondition = true
next()
})
.catch((data) => {
...
next()
})
}在快递处理程序:
app.post('/query', checkPrecondition, cors(), (req, res, next) => {
if(!req.precondition){
res.status(400).send(JSON.stringify({status: 'insufficient'}))
return
}
res.redirect('target.host')
})感谢您澄清了CORS问题。
https://stackoverflow.com/questions/54933492
复制相似问题