在请求完成数据处理之后Nodejs做出响应

我想根据我收到的完成的请求而有所不同。 我正在发送POST请求并收到一个XML文件。 结果是成功或错误。 我使用xml2json将xml转换成json对象,然后根据我想要输出json的响应。

问题是,我不能在响应内部有一个响应。 我也不能保存callback的价值供以后使用(因为它的asynchronous)。

我曾经想过使用Promise,但我不确定。 我该怎么办?

操作顺序应该是

1)发送请求

2)获取缓冲区响应

3)join缓冲区。 将xml处理成JSON

4)根据JSON条目的types,如果xml响应res.json('error') ,则输出res.json('success')res.json('error')

 app.post('/api/submit', (req, res) => { ... const request = https.request(options, (res) => { let chunks = []; res.on("data", function(chunk) { chunks.push(chunk); }); res.on("end", function(err) { if (err) throw err; let body = Buffer.concat(chunks); xmlConverter(body, function(err, result) { console.dir(result); if (result.entry) { console.log('✅ Success') //Respond with json here --> res.json('success') } else if (result.error) { console.log('There was an error processing your request'); //or here if there was an error --> res.json('error') } }); }); }); request.end() 

你可以在callback里面回应。 问题是,你有两个variables,都命名res ,所以一个阴影另一个。 你只需要改变其中的一个resvariables名称,以免影响它。 例如,您可以更改:

 const request = https.request(options, (http_res) // <--change argument name 

后来:

 if (result.entry) { console.log('✅ Success') http_res.json('success') // <-- use the response object from request 

以后不能保存结果的问题是一个不同的问题,但容易解决。 解决scheme虽然真的取决于你想要做什么。 例如,如果要进一步处理数据,则可以设置一个函数来调用并传递响应数据。例如:

 function process_data(response){ // use the response here } 

那么你可以简单地在获取数据时调用它:

 if (result.entry) { console.log('✅ Success') http_res.json('success') // <-- use the response object from request process_data(result) 

当然,也许你的用例更复杂,但没有更多的细节,很难给出具体的答案。

不要使用相同的名称,因为它们是不同的variables。 只需使用out resvariables来响应具有所需值的请求。 我认为这将是这样的:

 app.post('/ api/submit', (req, res) => { ... const request = https.request(options, (resValue) => { let chunks = []; resValue.on("data", function(chunk) { chunks.push(chunk); }); resValue.on("end", function(err) { if (err) throw err; let body = Buffer.concat(chunks); xmlConverter(body, function(err, result) { console.dir(result); if (result.entry) { console.log('✅ Success') res.json('success') } else if (result.error) { console.log('There was an error processing your request'); res.json('error') } }); }); }); request.end() 

究竟是什么问题? 您完全可以重命名提供给https.request(options,callbackFunction)的callback函数的参数 – 这个variables的名称并不重要。

 app.post('/api/submit', (req, res) => { const request = https.request(options, (potato) => { let chunks = []; potato.on("data", function(chunk) { chunks.push(chunk); }); potato.on("end", function(err) { if (err) throw err; // TODO res.status(500).json({}); ?? let body = Buffer.concat(chunks); xmlConverter(body, function(err, result) { console.dir(result); if (result.entry) { console.log('✅ Success') res.status(200).json({}); } else if (result.error) { console.log('There was an error processing your request'); res.status(500).json({}); } request.end() }); }); }); });