我如何 return Unirest 的函数值并使用 Express 发送?

How do I return the value of a function that Unirest and send that using Express?

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

我 运行 遇到了我编写的函数没有将数据返回到前端的问题 (Screenshot of inspector) even though the function is running correctly in the back end side (Screenshot of Terminal)。

目前转换代码如下:

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

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

现在在你的 express 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)
      })
  });