2017-06-18 91 views
0

我有以下代碼從我的index.html文件中的表單獲取輸入,然後將POSTs轉換爲運行在localhost:8080的節點腳本。然後節點腳本接受輸入並通過調用LUIS.ai API來查詢它,然後將響應發回。但是,回覆需要很長時間才能顯示,我必須刷新頁面並確認表單提交以獲取結果。有沒有更有效的方法來做到這一點。我是Node.js的新手。提交表單提交後在Node.js中發送響應的有效方式

app.js

//Modules 
var express = require('express'); 
var bodyParser = require('body-parser'); 
var request = require('request'); 
var http = require('http'); 

//Variables and definitions 
var app = express(); 
var query = null; 
//LUIS.ai URL 
var luisURL = "LUIS_API_URL"; 
var intent = null; 

//body-parser 
app.use(bodyParser.urlencoded({ extended: true })); 

//Get and handle LUIS.ai data 
function getLUISData(urlLUIS){ 
    //Get LUIS.ai JSON data 
    request({url:urlLUIS, json:true}, function (error, response, body) { 
     intent = body 
    }); 
    return intent; 
} 

//Get query from HTML form 
app.post('/query', function(request, response) { 
    query = request.body.query; 
    luisURL = luisURL.concat(encodeURIComponent(query)); 
    var data = getLUISData(luisURL); 
    response.send(data); 
}); 

app.listen(8080); 

的index.html

<!DOCTYPE html> 
<html> 
<body> 
    <form action="http://127.0.0.1:8080/query" method="post"> 
     <input type="text" name="query"/> 
     <input type="submit" value="Submit" /> 
    </form> 
</body> 
</html> 
+0

請求是異步的。嘗試提出請求。 –

+0

@Dinesh對不起,我是node.js的新手,我該怎麼做? –

回答

1

用承諾來處理異步。您可以閱讀更多關於諾言here

function getLUISData(urlLUIS){ 
     //Get LUIS.ai JSON data 
    return new Promise((resolve, reject) => { 
     request({url:urlLUIS, json:true}, function (error, response, body) { 
      if (err) return reject(err); 
      try { 
       resolve(body); 
      } catch(e) { 
       reject(e); 
      } 
     });//end of request 

    });//end of promise 
} 

app.post('/query', function(request, response) { 
    query = request.body.query; 
    luisURL = luisURL.concat(encodeURIComponent(query)); 
    getLUISData(luisURL).then(function(data){ // execution will wait here until request completes. here promise gives you data. 
     response.send(data); 
    }); 
}); 
+0

謝謝你完美的工作! –

+0

不客氣。@ NikhilRaghavendra –