ZMath_lin ZMath_lin - 1 month ago 12
Node.js Question

nodejs connect mysql error

I use mysql and express to write a easy login system.

database.js:

var mysql = require('mysql');
var config = require('../config/config');

var pool = mysql.createPool(config.mysql_dev);

var query=function(sql,callback){
pool.getConnection(function(err,conn){
if(err) console.log("POOL ==> " + err);
else{
conn.query(sql,function(qerr,vals,fields){
//release connection
conn.release();
callback(qerr,vals,fields);

});
}
});
};

module.exports=query;


index.js:

router.post('/login',function(req,res){
var query = require('../modules/database');
query("select * from managers where ManagerID =10001",function(err,vals,fields){
var temp=JSON.stringify(vals);

var manager = JSON.parse(temp)[0];

if(req.body.password===manager.password){
req.session.manager = manager;
res.redirect('/home');
}
res.send('ID or password wrong!');
});
});


However, everytime when i get this error:

/opt/workspace/project/nodejs-demo/node_modules/mysql/lib/protocol/Parser.js:77
throw err; // Rethrow non-MySQL errors
^

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/opt/workspace/project/nodejs-demo/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/opt/workspace/project/nodejs-demo/node_modules/express/lib/response.js:163:12)
at /opt/workspace/project/nodejs-demo/routes/index.js:40:7
at Query._callback (/opt/workspace/project/nodejs-demo/modules/database.js:16:17)
at Query.Sequence.end (/opt/workspace/project/nodejs-demo/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at Query._handleFinalResultPacket (/opt/workspace/project/nodejs-demo/node_modules/mysql/lib/protocol/sequences/Query.js:144:8)
at Query.EofPacket (/opt/workspace/project/nodejs-demo/node_modules/mysql/lib/protocol/sequences/Query.js:128:8)
at Protocol._parsePacket (/opt/workspace/project/nodejs-demo/node_modules/mysql/lib/protocol/Protocol.js:280:23)
at Parser.write (/opt/workspace/project/nodejs-demo/node_modules/mysql/lib/protocol/Parser.js:73:12)


How to solve it?
I do not know how to solve it and search for a long time.
If i describe it not clearly, just comment and i will add anything i know.

Answer

I explained your problem in comments in code.

router.post('/login',function(req,res){ 
    var query = require('../modules/database');
    query("select * from managers where ManagerID =10001",function(err,vals,fields){  
        var temp=JSON.stringify(vals);

        var manager = JSON.parse(temp)[0];

        if(req.body.password===manager.password){
           req.session.manager = manager;


           //You are redirecting user to home
           res.redirect('/home');

           //You should add 'return'
           return;
        }

        //This will only accessible if password is not match
        res.send('ID or password wrong!');
    });
});