我认为我有愚蠢的问题,但我不知道如何解决这个问题。在express中的一篇文章中,我想向另一个服务器发送两个请求,我想得到两个客户端响应(在我的情况下是角度)。我尝试制作两个res.send(body)
,但我收到错误Error: Can't set headers after they are sent.
而我的问题是:这两个回复是否可能抛出并进入一个回复?
router.post('/paynow', function(req, res){
request({
method: 'POST',
url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: "xyz"
}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
res.send(body);
}
)
request({
method: 'GET',
url: 'https://secure.snd.payu.com/api/v2_1/paymethods/',
headers: {
'Authorization': 'xyz'
}}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
res.send(body);
}
),
})
答案 0 :(得分:0)
您无法发送两个回复。但是您可以将两个请求结果合并到一个响应中。尝试使用promises:
router.post('/paynow', function(req, res){
Promise.all([
new Promise((resolve, reject) => {
request({
method: 'POST',
url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: "xyz"
}, function (error, response, body) {
if (error) return reject(error)
resolve(body)
})
}),
new Promise((resolve, reject) => {
request({
method: 'POST',
url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: "xyz"
}, function (error, response, body) {
if (error) return reject(error)
resolve(body)
})
})
]).then(listOfResponses => {
res.json(listOfResponses)
})
})
答案 1 :(得分:0)
很棒....首先你不能发送多个响应。即 res.send 一次&只有一次!! ......
所以你可以做的是......首先应该优先执行...在你的情况下首先执行授权然后 paymethods
所以正确的顺序是
$.ajax{
url : /authorize,
type : post,
data : /same data,
, success : function(response) {
//within successs make pay method request as another ajax using the
// response from previous authorize request
$.ajax{
url : /paymethods,
data : response
}
}
}
同样将您的路线分开..
router.post('/authorize', function(req, res){
request({
method: 'POST',
url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: "xyz"
}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
res.send(body);
}
)}
和
router.post('/paynow', function(req, res){
request({
method: 'GET',
url: 'https://secure.snd.payu.com/api/v2_1/paymethods/',
headers: {
'Authorization': 'xyz'
}}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
res.send(body);
}
)
}