【问题标题】:Post request returns undefined on the server side发布请求在服务器端返回未定义
【发布时间】:2017-11-27 10:50:45
【问题描述】:

所以,我提出了这个 POST 请求

$("#pacotes").on('click', ".produto", function () {
    console.log(this.id);
    $.post("http://localhost:3000/pacote?idPacote=" + this.id);
});

日志在客户端返回一个数字,这是应该的。

然后帖子通过我的路线到达这里

exports.Pacote = function (req, res) {
    console.log("gato");
    var pacote = req.idPacote;
    console.log(pacote);
    connection.connection();
    global.connection.query('SELECT * FROM Pacote WHERE idPacotes = ? LIMIT 1', [pacote], function (err, result) {
    if (result.length > 0) {
         if (result) {
              var object = JSON.parse(JSON.stringify(result));
              var packObject = object[0];
              if (result.length > 0) {
              if (result) {
                   res.render('home', { title: 'pacote', layout: 'pacote', data: packObject  });
              }
         }   
     } else if (err) {
      console.log(err);
     }
   };
   });
}

第一个日志只是一个标志,看它是否到达了点,它是 但是第二个日志应该返回一个数字,但它返回的是 undefined

我在这个主题上不是很有经验,但这一直对我有用。 我不明白我的不同之处,因为我的登录功能几乎相同,并按预期返回实际值。也许是因为bodyparser,但我不知道。

id 在客户端正确返回但在服务器端未定义,这让我很困扰

我也尝试了同样的事情,但使用 GET 并且结果没有改变

【问题讨论】:

  • 请在此处发布您的路线定义。

标签: javascript jquery mysql node.js post


【解决方案1】:

您在查询字符串中传递“idPacote”。如果您将 Express 与 NodeJS 一起使用,您将在“req.query”中获得查询字符串参数。试试这个

var pacote = req.query.idPacote;

而不是

var pacote = req.idPacote;

【讨论】:

    【解决方案2】:

    var pacote = req.idPacote; 应替换为(前提是您将其作为GET 参数发送):

    var pacote = req.params.idPacote;
    

    附注:您应该使用连接池来提高应用的性能,例如:

    var mysql = require("mysql");    
    //Database connection parameters
    var config = {
        connectionLimit: 10000, 
        host: "127.0.0.1",
        user: "user",
        password: "password",
        database: "database",
        charset: "utf8_general_ci",
        connectTimeout: 4000
    };   
    //Pool
    var pool  = mysql.createPool(config);           
    function connection(){
        //Assign connection pool for further reuse
        this.init = function () {       
            this.pool = pool;       
        };
        //Get connection
        this.acquire = function(callback){      
            this.pool.getConnection(function(error, con){
                if (error) {
                    if (this.pool) 
                        //Close all connections in pool
                        this.pool.end(function(err){});
                    console.log("\x1b[31m" + error, "\x1b[0m");             
                }
                else {
                    callback(error, con);
                }
            });         
        };
    }
    

    阅读更多here

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 2016-02-27
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 2019-04-08
      • 2021-01-14
      相关资源
      最近更新 更多