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

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

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

  1. const http = require('http');
  2. const express = require('express');
  3. const bodyParser = require('body-parser');
  4. const app = express();
  5. const sqlHelper = require('./sqlHelper');
  6. app.use(bodyParser.json());
  7. app.post('/registeruser',(req,res)=>{
  8. const userName = req.body.username;
  9. const password = req.body.password;
  10. const firstName = req.body.firstname;
  11. const lastName = req.body.lastname;
  12. const userDetail = {
  13. userName,
  14. password,
  15. firstName,
  16. lastName
  17. }
  18. sqlHelper.addUserSQL(userDetail,res);
  19. res.send("User Registerd Seccesfuly");
  20. })
  21. const server = http.createServer(app);
  22. server.listen(3000);

Below is my sqlHelper.js code

  1. const mysql = require('mysql2');
  2. const addUserSQL = (userDetail,res) => {
  3. const con = mysql.createConnection({
  4. host:'localhost',
  5. user:'root',
  6. password:'mysqlpw',
  7. multipleStatements: true
  8. });
  9. con.connect(function(err){
  10. if(err)
  11. throw err
  12. console.log("CHECKING IF USER ALREADY EXIST");
  13. let sql = `USE mydatabase; SELECT * FROM usertable WHERE username=?`;
  14. con.query(sql,[userDetail.userName],function(err,result){
  15. if(err)
  16. throw err;
  17. if(result[1]!=[]){
  18. res.send("ERROR: USERNAME ALREADY EXISTS");
  19. }
  20. })
  21. })
  22. }
  23. 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

  1. const http = require('http');
  2. const express = require('express');
  3. const bodyParser = require('body-parser');
  4. const app = express();
  5. const sqlHelper = require('./sqlHelper');
  6. app.use(bodyParser.json());
  7. app.post('/registeruser',(req,res)=>{
  8. const userName = req.body.username;
  9. const password = req.body.password;
  10. const firstName = req.body.firstname;
  11. const lastName = req.body.lastname;
  12. const userDetail = {
  13. userName,
  14. password,
  15. firstName,
  16. lastName
  17. }
  18. sqlHelper.addUserSQL(userDetail,res);
  19. res.send("User Registerd Seccesfuly");
  20. })
  21. const server = http.createServer(app);
  22. server.listen(3000);

Below is my sqlHelper.js code

  1. const mysql = require('mysql2');
  2. const addUserSQL = (userDetail,res) => {
  3. const con = mysql.createConnection({
  4. host:'localhost',
  5. user:'root',
  6. password:'mysqlpw',
  7. multipleStatements: true
  8. });
  9. con.connect(function(err){
  10. if(err)
  11. throw err
  12. console.log("CHECKING IF USER ALREADY EXIST");
  13. let sql = `USE mydatabase; SELECT * FROM usertable WHERE username=?`;
  14. con.query(sql,[userDetail.userName],function(err,result){
  15. if(err)
  16. throw err;
  17. if(result[1]!=[]){
  18. res.send("ERROR: USERNAME ALREADY EXISTS");
  19. }
  20. })
  21. })
  22. }
  23. 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:

  1. app.post('/registeruser', async (req, res) => {
  2. const userName = req.body.username;
  3. const password = req.body.password;
  4. const firstName = req.body.firstname;
  5. const lastName = req.body.lastname;
  6. const userDetail = {
  7. userName,
  8. password,
  9. firstName,
  10. lastName
  11. }
  12. const { err } = await sqlHelper.addUserSQL(userDetail);
  13. if (err) return res.status(500).send(err);
  14. res.send("User Registered Successfully");
  15. })

Changes in sqlHelper file:

  1. const mysql = require('mysql2/promise');
  2. const options = {
  3. host: 'localhost',
  4. user: 'root',
  5. password: 'mysqlpw',
  6. multipleStatements: true
  7. };
  8. const addUserSQL = async (userDetail) => {
  9. const connection = await mysql.createConnection(options);
  10. const query = `USE mydatabase; SELECT * FROM usertable WHERE username=?`;
  11. const [rows, fields] = await connection.execute(query, [userDetail.userName]);
  12. if (rows?.length > 0) {
  13. return { err: "ERROR: USERNAME ALREADY EXISTS" };
  14. } else {
  15. // Code to create a user entry in your db
  16. }
  17. }
  18. 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:

  1. app.post('/registeruser',async (req,res)=>{
  2. const userName = req.body.username;
  3. const password = req.body.password;
  4. const firstName = req.body.firstname;
  5. const lastName = req.body.lastname;
  6. const userDetail = {
  7. userName,
  8. password,
  9. firstName,
  10. lastName
  11. }
  12. const {err} = await sqlHelper.addUserSQL(userDetail);
  13. if(err) return res.status(500).send(err);
  14. res.send("User Registerd Seccesfuly");
  15. })

Changes in sqlHelper file:

  1. const mysql = require('mysql2/promise');
  2. const options = {
  3. host:'localhost',
  4. user:'root',
  5. password:'mysqlpw',
  6. multipleStatements: true
  7. };
  8. const addUserSQL =async (userDetail) => {
  9. const connection = await mysql.createConnection(options);
  10. const query = `USE mydatabase; SELECT * FROM usertable WHERE username=?`;
  11. const [rows, fields] = await connection.execute(query, [userDetail.userName]);
  12. if(rows?.length>0){
  13. return {err: "ERROR: USERNAME ALREADY EXISTS" };
  14. }else{
  15. //code to create user entry in your db
  16. }
  17. }
  18. 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:

确定