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

标签 javascript node.js forms

我有以下代码,它从我的 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/

相关文章:

javascript - 如何在react中使用settimeout方法?

javascript - Angularjs:预览净化后的 html

node.js - Socketcan+ Express.js +Node.js 获取/发送 Can-Bus 消息

javascript - 如何同时在另一个字段中复制表单字段文本输入

forms - Angular2 - 如何将表单上的 `touched` 属性设置为 true

javascript - [Vue 警告] : Cannot find element: #app - Vue. js 2

Javascript:在 'onload' 事件之后应用的事件处理程序如何处理页面完全加载之前发生的事件?

node.js - 在共享托管计划上安装 NodeJS 的问题

node.js - 如何在 Sequelize 中获得超出 promise 的结果?

Drupal:如何在 hook_field_widget_form 中使用字段集