简体   繁体   中英

Cannot call method 'send' of undefined(response is undefined) in express js

I have tried to pass a variable from my index.html to the database(maildata.js) through app.js(server) and get the corresponding data I am able to get the data from the database but couldnt send that back to the server(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);    
      }    
    });
   }    
  });    
 }    
});    
}

Thanks in Advance

调用函数时如何发送响应?

var result=maildata.getMailData(input); // something missing here

Your getMailData function expects two arguments:

exports.getMailData=function(data,response) { ... }

but you give it only one:

var result=maildata.getMailData(input); 

Which makes the value of the response argument undefined .

Here is what you should do:

app.post('/mailboxpost',function(request, response) {
  var input=request.query.search;     
  maildata.getMailData(input, response); 
});

and let maildata.getMailData handle the response sending, as you did in response.send(result);

I have used asynchronous callback method in my app.js.

I got the result

var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});

Thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM