mysql - Return error response in nodejs -


evening stack! tonight decided play around nodejs , i'm having little trouble understanding appropriate way me handle errors in situation.

i have table stores playername , name must unique. rather try insert , error, want first make select , if result, return 400 user , let them know name exists. if not, continue on normal, insert name, , return 203.

what i've got isn't working. i've attempted try/catch , didn't work. , can't return error methods i'm using. what's way go this?

router.post('/addplayer' , function(req, res, next){   var playername = req.body.name;   if(playername === undefined || playername.length === 0)   {     return res.status(400).send('no name provided');   }    var query = 'select name players name ?';   var inserts = [playername];   query = connection.format(query , inserts);   connection.query(query, function(err, results){     if(err) return res.status(500).send('error connecting database.');      if(results.length !== 0) return res.status(400).send('this name has been used.');   });    query = 'insert players (name) values(?)';   inserts = [playername];   query = connection.format(query , inserts);   connection.query(query, function(err){     if(err) return res.status(500).send('error connecting database.');   });    res.status(201).send("added player: " + playername); }); 

in current version obvious problem node crashes complaining not being able set headers after they've been sent. know need do. end execution of route , return error browser, i'm not clear on how best go that.

i'm using express framework , mysql.

thanks.

the problem you're running both queries in parallel. insert executed before response of select received. means there race condition. both queries tries send res.status() 1 happen after other causes error.

to fix this, wait until select received insert:

var query = 'select name players name ?'; var inserts = [playername]; query = connection.format(query , inserts); connection.query(query, function(err, results){     if(err) return res.status(500).send('error connecting database.');      if(results.length !== 0) return res.status(400).send('this name has been used.');      query = 'insert players (name) values(?)';     inserts = [playername];     query = connection.format(query , inserts);     connection.query(query, function(err){         if(err) return res.status(500).send('error connecting database.');          res.status(201).send("added player: " + playername);     }); }); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -