简体   繁体   English

nodejs:res.send() 可以从调用的 function 完成吗?

[英]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.我是 Node.JS 的新手,我正在尝试编写一个 API,它在检查用户名是否已存在后将用户数据存储在数据库中。 Below is my app.js code下面是我的 app.js 代码

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下面是我的 sqlHelper.js 代码

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.当请求的用户名已经在我的数据库中时,我得到以下响应用户注册成功而不是错误:USERNAME ALREADY EXISTS并且在终端中出现错误无法在将标题发送到客户端后设置标题。 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.您永远不应该从被调用的 function 执行 res.send。

Instead,You should return error from your sqlhelper code.相反,您应该从 sqlhelper 代码返回错误。

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: sqlHelper 文件中的更改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM