如何从执行 req.write() 的快速路由发送回响应?



我正在通过XML使用TextBroker的API,并且必须编写的数据感觉比使用RESTful API设置非常不正常。


exports.getPendingOrders = (req, res) => {
genCrypt()
.then(encryptedAuth => {
let requestEnvelope = `
<soapenv:Envelope 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:urn="urn:budgetOrderService">n   
<soapenv:Header/>n   
<soapenv:Body>n      
<urn:create soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">nt    
<salt xsi:type="xsd:string">${encryptedAuth.salt}</salt>n         
<token xsi:type="xsd:string">${
encryptedAuth.token
}</token>n         
<budget_key xsi:type="xsd:string">${
config.budgetKey
}</budget_key>n         
<category xsi:type="xsd:positiveInteger">1</category>n         
<title xsi:type="xsd:string">TEST from API 49</title>n         
<description xsi:type="xsd:string"><![CDATA[Nothing much<h1></h1>]]></description>n         
<min_words xsi:type="xsd:positiveInteger">1</min_words>n         
<max_words xsi:type="xsd:positiveInteger">100</max_words>n         
<classification xsi:type="xsd:positiveInteger">4</classification>n         
<working_time xsi:type="xsd:positiveInteger">2</working_time>n         
<author xsi:type="xsd:positiveInteger">756</author>n         
<note xsi:type="xsd:string">Nothing</note>n         
<deadline xsi:type="xsd:date"></deadline>n      
</urn:create>n   
</soapenv:Body>n
</soapenv:Envelope>
`;
return requestEnvelope;
})
.then(envelope => {
var options = {
method: "POST",
hostname: "api.textbroker.com",
path: "/Budget/budgetOrderService.php",
headers: {
"Content-Type": "application/xml",
"cache-control": "no-cache"
}
};
const request = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
// res.on("end", function() {
//   console.log(body.toString());
// });
});
request.write(envelope);

});
};

在生成盐和从我的配置中获取内容方面,一切似乎都起作用。我可以添加res.on('end')和控制台日志chunks的正文,但我想将数据发送回前端,以便我可以用它做一些事情。

究竟如何做到这一点?

我建议将你的http请求变成一个承诺,如下所示:

function saveData(options) {
return new Promise(function(resolve, reject) {
http.request(options, function(res) {
var chunks = []
res.on('data', function(chunk) {
chunks.push(chunk)
})
res.on('end', function() {
// the whole response has been received, so call `resolve` here
const data = chunks.toString() // or whatever you want to pass back
resolve(data)
})
})
.on('error', err => { 
reject(err)    
})
})
} 

然后,在代码中,可以像这样调用此函数:

exports.getPendingOrders = (req, res) => {
genCrypt()
.then(encryptedAuth => { ... })
.then(envelope => {
var options = { ... }
return saveData(options)
})
.then(result => {
// send it however you need it to the client
// as an example, I am sending it as JSON
res.status(200).json({ 
data: result 
})
})
}

这样,您将在调用res.json()并发回响应之前从 http 调用中获得结果。


我无法从您的代码中完全弄清楚如何使用envelope,或者如果您尝试发送(向客户端)从 http 请求中获得的数据,为什么要做request.write(envelope),但这应该给你一个想法。

最新更新