问题描述
我正在为我的编码训练营开发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)); });
1楼
jremi
0
已采纳
2019-02-25 02:39:54
// 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)
})
});