![](/img/trans.png)
[英]Coffeescript + Express.js : cannot call method 'sliced' of undefined
[英]Cannot call method 'send' of undefined(response is undefined) in express js
我試圖通過app.js(server)將變量從index.html傳遞到數據庫(maildata.js)並獲取相應的數據,我能夠從數據庫中獲取數據,但無法將其發送回服務器(app.js)
app.js
var express = require('express');
var maildata= require('./maildata');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/', function(request, response){
response.sendfile(__dirname + '/mailbox.html');
});
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
var result=maildata.getMailData(input);
response.send(result);
response.end();
});
app.listen(8888);
console.log('Server is running on port 8888');
maildata.js
exports.getMailData=function(data,response) {
var stop_name= data;
connection.query("select stop_name,stop_comment from stoplist where stop_name= '"+stop_name+"' limit 1",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString1= JSON.stringify(rows);
connection.query("select mailbox_sequence_no from stoplist where stop_name= '"+stop_name+"'",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString2 = JSON.stringify(rows);
connection.query("select party_head from stoplist where stop_name= '"+stop_name+"'", function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString3 = JSON.stringify(rows);
var result=jsonString1+'/'+jsonString2+'/'+jsonString3;
response.send(result);
}
});
}
});
}
});
}
提前致謝
調用函數時如何發送響應?
var result=maildata.getMailData(input); // something missing here
您的getMailData
函數需要兩個參數:
exports.getMailData=function(data,response) { ... }
但您只給它一個:
var result=maildata.getMailData(input);
這使得response
參數的值undefined
。
這是您應該做的:
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
maildata.getMailData(input, response);
});
並讓maildata.getMailData
處理響應發送,就像您在response.send(result);
所做的一樣response.send(result);
我在我的app.js中使用了異步回調方法。
我得到了結果
var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});
謝謝大家
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.