如何返回Unirest的函数值并使用Express发送该值?

时间:2019-02-25 01:07:16

标签: javascript json express unirest

我正在为我的编码训练营开发Language Translation应用程序。我在后端使用Microsoft Text Translations API来转换用户输入,以获得每个查询所需的输出。

我遇到了这样一个问题,即即使该函数在后端{{3}中正确运行,但我编写的函数并没有将数据返回到前端(Screenshot of inspector)中}。

当前是转换代码:

function langTranslateJSON(startLang, endLang, textString) {
  let queryURL = `https://microsoft-azure-translation-v1.p.rapidapi.com/translate?from=${startLang}&to=${endLang}&text=${textString}`;
  unirest
    .get(queryURL)
    .header(
      "X-RapidAPI-Key",
      API_KEY
    )
    .end(result => {
    //data comes back as an XML string //
      let xmlString = result.body 
      
      parseString(xmlString, function (err, data) {
        console.log(data)
        return data
      })
    })
}

这是到用户的POST路由

 //Using Express//
 
 app.post("/api/Translate", function (req, res) {
    res.send(langTranslate.langTranslateJSON(
      req.body.translateFromLanguage,
      req.body.translateToLanguage,
      req.body.translateFrom));
  });

1 个答案:

答案 0 :(得分:0)

// notice 4th callback argument after textString argument
function langTranslateJSON(startLang, endLang, textString, callback) {
  let queryURL = `https://microsoft-azure-translation-v1.p.rapidapi.com/translate?from=${startLang}&to=${endLang}&text=${textString}`;
  unirest
    .get(queryURL)
    .header(
      "X-RapidAPI-Key",
      API_KEY
    )
    .end(result => {
    //data comes back as an XML string //
      let xmlString = result.body 

      parseString(xmlString, function (err, data) {
        console.log(data)
        // Fire the callback here and pass in the data result
        callback(data);
      })
    })
}

现在在您的快速POST路由中,您需要传递回调函数

 app.post("/api/Translate", function (req, res) {
  // first you call your langTraslateJSON method
  // notice the 4th argument is now passing in the callback function
  // when your method is run it will invoke the callback you are passing here
  // and pass the data to the callback. 
  // It will then invoke the Express res.send method with this data  
  langTranslate.langTranslateJSON(
      req.body.translateFromLanguage,
      req.body.translateToLanguage,
      req.body.translateFrom, function(myDataResponse){
         res.send(myDataResponse)
      })
  });