gpt4 book ai didi

javascript - 表单提交后在 Node.js 中发送响应的有效方法

转载 作者:行者123 更新时间:2023-12-03 04:04:40 29 4
gpt4 key购买 nike

我有以下代码,它从我的 index.html 中的表单获取输入文件,然后 POSTs它到在 localhost:8080 运行的 Node 脚本。然后, Node 脚本获取输入并通过调用 LUIS.ai API 对其进行查询,然后发回响应。但是,响应需要很长时间才能显示,我必须刷新页面并确认表单提交才能获得结果。有没有更有效的方法来做到这一点。我是 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>

最佳答案

使用 Promise 来处理异步。您可以阅读更多关于promise 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);
});
});

关于javascript - 表单提交后在 Node.js 中发送响应的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611382/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com