Im a noob to nodejs and trying to write an api which stores user data in sql after checking if the username already exists. below is my app.js code
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const sqlHelper = require('./sqlHelper');
app.use(bodyParser.json());
app.post('/registeruser',(req,res)=>{
const userName = req.body.username;
const password = req.body.password;
const firstName = req.body.firstname;
const lastName = req.body.lastname;
const userDetail = {
userName,
password,
firstName,
lastName
}
sqlHelper.addUserSQL(userDetail,res);
res.send("User Registerd Seccesfuly");
})
const server = http.createServer(app);
server.listen(3000);
this is my sqlHelper.js code
const mysql = require('mysql2');
const addUserSQL = (userDetail,res) => {
const con = mysql.createConnection({
host:'localhost',
user:'root',
password:'mysqlpw',
multipleStatements: true
});
con.connect(function(err){
if(err)
throw err
console.log("CHECKING IF USER ALREADY EXIST");
let sql = `USE mydatabase; SELECT * FROM usertable WHERE username=?`;
con.query(sql,[userDetail.userName],function(err,result){
if(err)
throw err;
if(result[1]!=[]){
res.send("ERROR: USERNAME ALREADY EXISTS");
}
})
})
}
module.exports={addUserSQL};
here for request with username that is already in sql I am getting a response of User registered successfully instead of ERROR: USERNAME ALREADY EXISTS and a error in terminal Cannot set headers after they are sent to the client. How can i write this code in a proper way to check if username already existing and send a apt response back?
CodePudding user response:
A straight answer your question is NO
You should never do res.send from function being called.
Instead,You should return error from your sqlhelper code.
Try this code:
app.post('/registeruser',async (req,res)=>{
const userName = req.body.username;
const password = req.body.password;
const firstName = req.body.firstname;
const lastName = req.body.lastname;
const userDetail = {
userName,
password,
firstName,
lastName
}
const {err} = await sqlHelper.addUserSQL(userDetail);
if(err) return res.status(500).send(err);
res.send("User Registerd Seccesfuly");
})
Changes in sqlHelper file:
const mysql = require('mysql2/promise');
const options = {
host:'localhost',
user:'root',
password:'mysqlpw',
multipleStatements: true
};
const addUserSQL =async (userDetail) => {
const connection = await mysql.createConnection(options);
const query = `USE mydatabase; SELECT * FROM usertable WHERE username=?`;
const [rows, fields] = await connection.execute(query, [userDetail.userName]);
if(rows?.length>0){
return {err: "ERROR: USERNAME ALREADY EXISTS" };
}else{
//code to create user entry in your db
}
}
module.exports={addUserSQL};