为什么我的node.js代码在从用户处获取值时在第一个请求中没有给出响应?

qxgroojn  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(267)

在这段代码中,我向包含email id的服务器发送post请求,并使用该email id从数据库中检索信息。我是从 Postman 那里测试的”http://127.0.0.1:80/echo“在发送请求后,请求第一次显示为响应

{
    "source": "webhook-echo-sample"
}

第二次它给了我正确的结果

{
    "speech": "Name:xyz Mobile.no:123456789Address:qweCollege:azx Email:cvb@gmail.com",
    "source": "webhook-echo-sample"
}

为什么我对api的第一个请求会失败?

"use strict";
const express = require("express");
const restService = express();
const bodyParser = require("body-parser");
const os = require('os');

var mysql = require("mysql");
var final;
var Name = "Name:";
var Mobileno = "Mobile.no:";
var College = "College:";
var Address = "Address:";
var Email = "Email:";

restService.use(
    bodyParser.urlencoded({
        extended: true
    })
);

restService.use(bodyParser.json());
restService.post("/echo", function(req, res) {

    var con = mysql.createConnection({
        host: "abc.com",
        user: "xyz123",
        password: "123456",
        database: "seller1"
    });
    var email = req.body.result.parameters.echoText
    var sql = 'SELECT * FROM seller1 WHERE email_id=' + mysql.escape(email);
    con.query(sql, function(error, results) {
        if (!error) {
            for (var i = 0; i <= results.length - 1; i++) {
                final = Name + results[i].Name + "\n" + Mobileno + results[i].mobile_no + "\n" + Address + results[i].Address + "\n" + College + results[i].College + "\n" + Email + results[i].email_id;
            }
        } else {
            return [];
        }
    });

    return res.json({
        "speech": final,
        "source": "webhook-echo-sample"
    });
});

restService.listen(process.env.PORT || 80, function() {
    console.log("Server up and listening");
});
qeeaahzv

qeeaahzv1#

我想这是因为我的天性
试着在里面发送响应!错误检查如下所示

restService.post("/echo", function(req, res) {

    var con = mysql.createConnection({
        host: "abc.com",
        user: "xyz123",
        password: "123456",
        database: "seller1"
    });
    var email = req.body.result.parameters.echoText
    var sql = 'SELECT * FROM seller1 WHERE email_id=' + mysql.escape(email);
    con.query(sql, function(error, results) {
        if (!error) {
            for (var i = 0; i <= results.length - 1; i++) {
                final = Name + results[i].Name + "\n" + Mobileno + results[i].mobile_no + "\n" + Address + results[i].Address + "\n" + College + results[i].College + "\n" + Email + results[i].email_id;
            }
            return res.json({
              "speech": final,
              "source": "webhook-echo-sample"
            });
        } else {
            return [];
        }
    }); 
});

相关问题