nodejs: 能否从被调用的函数中使用 res.send()?

huangapple go评论74阅读模式
英文:

nodejs: can res.send() be done from a called function?

问题

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?

英文:

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?

答案1

得分: 0

A straight answer to your question is NO.

You should never do res.send from a function being called.

Instead, you should return an 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 Registered Successfully");
})

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 a user entry in your db
    }
}

module.exports = { addUserSQL };
英文:

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};

huangapple
  • 本文由 发表于 2023年1月5日 20:01:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75018077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定