2017-06-23 48 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