繁体   English   中英

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

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

我是 Node.JS 的新手,我正在尝试编写一个 API,它在检查用户名是否已存在后将用户数据存储在数据库中。 下面是我的 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);

下面是我的 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};

当请求的用户名已经在我的数据库中时,我得到以下响应用户注册成功而不是错误:USERNAME ALREADY EXISTS并且在终端中出现错误无法在将标题发送到客户端后设置标题。 如何以正确的方式编写此代码以检查用户名是否已存在并发回响应?

直接回答你的问题是否定

您永远不应该从被调用的 function 执行 res.send。

相反,您应该从 sqlhelper 代码返回错误。

试试这个代码:

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

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