Nodejs在数据处理完请求后响应

时间:2017-11-30 15:59:58

标签: javascript node.js asynchronous

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

问题在于我无法在回复中做出回应。我也无法保存回调的值以供以后使用(因为它是异步的)。

我曾考虑使用Promises,但我不确定。我该怎么办?

操作顺序应为

1)发送请求

2)获取缓冲区响应

3)加入缓冲区。将xml处理为JSON

4)根据JSON条目的类型,如果xml响应错误,则输出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()

3 个答案:

答案 0 :(得分:1)

不要对两个res使用相同的名称,因为它们是不同的变量。只需使用out res变量以您想要的值响应请求。 我认为会是这样的:

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()

答案 1 :(得分:1)

您可以在回调中做出回应。问题是你有两个名为res的变量,所以一个变量影响另一个变量。您只需要更改其中一个res变量名称,这样就不会影响它。例如,您可以更改:

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

以后无法保存结果的问题是另一个问题,但很容易解决。解决方案虽然取决于你想要做的事情。例如,如果您想要进一步处理数据,可以设置一个函数来调用并传递响应数据。例如:

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)

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

答案 2 :(得分:0)

究竟是什么问题?您完全能够重命名提供给https.request(options,callbackFunction)的回调函数的参数 - 这个变量的名称并不重要。

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()
      });
    });
  });
});