无法调用方法'发送'express js中未定义的(响应未定义)

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

本文关键字:未定义 响应 发送 调用 方法 express js      更新时间:2023-09-26

我试图通过app.js(服务器)将一个变量从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); 中所做的那样

我在app.js.中使用了异步回调方法

我得到了的结果

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

感谢所有