2017-06-23 47 views
0

后要求退货所以,我有这个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,结果没有改变

+0

请在这里发布你的路线定义。 –

回答

0

你传入“查询字符串中的“idPacote”。如果您使用Express和NodeJS,您将在“req.query”中获得查询字符串参数。试试这个

var pacote = req.query.idPacote; 

,而不是

var pacote = req.idPacote; 
+0

这工作,谢谢 – Rui

0

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