当前位置: 代码迷 >> JavaScript >> 如何返回Unirest的函数值并使用Express发送该值?
  详细解决方案

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

热度:42   发布时间:2023-06-05 10:29:30.0

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

我遇到的问题是,即使该函数在后端正常运行,我编写的函数也没有将数据返回到前端 。

当前是转换代码:

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

现在在您的快速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)
      })
  });
  相关解决方案