1. ホーム
  2. バックエンド
  3. ノード

expressはエラーを報告します。エラー [ERR_HTTP_HEADERS_SENT]: ヘッダがクライアントに送信された後、ヘッダを設定することができません。

2022-01-22 21:47:38
  1. // Handler function for registered users
  2. exports.regUser = (req, res) => {
  3. // 1. Determine if the username and password are empty
  4. // 1.1. Accepting form data
  5. const userinfo = req.body
  6. // 1.2. Determining whether data is legal
  7. if (!userinfo.username || !userinfo.password) {
  8. return res.send({
  9. status: 1,
  10. message: 'Username or password cannot be empty!
  11. })
  12. }
  13. // 2. Check if the username is occupied
  14. // 2.1. Import data manipulation module
  15. const db = require('. /db/index')
  16. // 2.2. Define the sql statement.
  17. const sql = 'select * from ev_users where username = ?'
  18. // 2.3. Execute the sql statement and determine if the username is occupied based on the result
  19. db.query(sql, userinfo.username, (err, results) => {
  20. // 2.4. Failed to execute sql statement
  21. if (err) return res.send({ status: 1, message: err.message })
  22. // 2.5. Username is occupied
  23. if (results.length === 1) return res.send({ status: 1, message: 'Username is occupied' })
  24. console.log('1');
  25. })
  26. I did not comment out the following res.send('reguser ok') used for testing when verifying if the username was taken, which caused res.send() to be called repeatedly, resulting in the error: Cannot set headers after they are sent to the client.
  27. //res.send('reguser ok')
  28. }