I'm new to Node.JS and I'm trying to write an API which stores user data in a database 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);
Below 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};
When there is a request with a username that is already in my database I get the following response 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 a username already exists and send a response back?
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};
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.