使用express-validator、express、mongoose和Next.js将标头发送到客户端后,无法设置标头

jpfvwuh4  于 2022-11-13  发布在  Go
关注(0)|答案(3)|浏览(170)

我正在next.js中使用express-validatormongoose构建一个登录/注册表单。
听说最佳做法是在前端 * 和 * 后端清理数据。
我在前端有一些验证(即检查是否通过Regex发送电子邮件,并确保密码在特定长度)。
但现在我想使用自定义验证器来检查我的mongodb数据库中是否存在电子邮件。

.post(body('username').custom(value => {
        UserModel.findOne({ 'email': value }).then(user => {
            if (user) {
                return Promise.reject('E-mail already in use');
            }
        });
    }),

这是我的代码的其余部分:

var router = require('express').Router()
var UserModel = require('../models/UserModel')
var { body } = require('express-validator');

router
    .route('/registration')
    .get(function(req, res) {
        UserModel.find({}, (err, users) => {
            if (err) res.status(500).send(err)
            res.json(users)
        })
    })
    .post(body('username').custom(value => {
        UserModel.findOne({ 'email': value }).then(user => {
            if (user) {
                return Promise.reject('E-mail already in use');
            }
        });
    }), async(req, res, next) => {

        try {
            let newUser = new UserModel(req.body)

            let savedUser = await newUser.save(err => {
                if (err) return res.json({ success: false, error: err })
                return res.json({ success: true })
            })

            if (savedUser) return res.redirect('/users/registration?success=true');
            return next(new Error('Failed to save user for unknown reasons'))

        } catch (err) {
            return next(err)
        }

    })

module.exports = router

这就是我得到的错误:

Error: Failed to save user for unknown reasons
    at router.route.get.post (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/users/index.js:34:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:267:15)
    at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/index.js:108:17
    at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
    at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
    at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:73:5)
    at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
    at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
    at Immediate.next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
    at Immediate.<anonymous> (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:635:15)
    at runCallback (timers.js:706:11)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

另外,当Mongoose在设计模型/模式时提供时,我是否需要它?

var mongoose = require('mongoose')
var emailValidator = require('email-validator')
var bcrypt = require('bcrypt') // hashing function dedicated for passwords

const SALT_ROUNDS = 12

var UserSchema = new mongoose.Schema(
  {
    username_email: {
      type: String,
      required: true,
      lowercase: true,
      index: { unique: true }, // I mean this!
      validate: {
        validator: emailValidator.validate,
        message: props => `${props.value} is not a valid email address`
      }
    },
    password: {
      type: String,
      required: true,
      trim: true,
      index: { unique: true },
      minlength: 8
    }
  },
  {
    timestamps: true
  }
)

UserSchema.pre('save', async function preSave(next) {
  var user = this
  var hash
  if (!user.isModified('password')) return next()
  try {
    hash = await bcrypt.hash(user.password, SALT_ROUNDS)
    user.password = hash
    return next()
  } catch (err) {
    return next(err)
  }
})

UserSchema.methods.comparePassword = async function comparePassword(candidate) {
  return bcrypt.compare(candidate, this.password)
};

module.exports = mongoose.model('User', UserSchema)

如果我不这样做,是否意味着检查电子邮件是否存在应该移动到前端?如果是这样的话,我将如何处理?

更新

我试过尼克的建议,但不知道为什么我仍然得到

`Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

以下是更新后的航线:

router
    .route('/registration')
    .get(function(req, res) {
        console.log(0)
        UserModel.find({}, (err, users) => {
            console.log(1)
            if (err) res.status(500).send(err)
            console.log(2)
            return res.json(users)
            console.log(3)
        })
    })
    .post(body('email').custom(value => {
        console.log(4)
        UserModel.findOne({ 'email': value }).then(user => {
            console.log(5)
            if (user) {
                console.log(6)
                return Promise.reject('E-mail already in use');
            }
        });
    }), async(req, res, next) => {
        console.log(7)
        try {
            let newUser = new UserModel(req.body)

            let savedUser = await newUser.save(err => {
                if (err) return res.json({ success: false, error: err })
                console.log(8)
                return res.json({ success: true })
            })
            console.log(9)
            if (savedUser) return res.redirect('/users/registration?success=true');
            console.log("savedUser ", savedUser);
            console.log(10)
            return next(new Error('Failed to save user for unknown reasons'))

        } catch (err) {
            return next(err)
        }

    })

Note that pages will be compiled when you first load them.
GET /_next/static/webpack/d691821e71bf01c860e6.hot-update.json 404 299.194 ms - 1862
GET /_next/static/webpack/42c7a9cb77dec12fc8a3.hot-update.json 200 40.276 ms - 35
4
7
9
savedUser  undefined
10
POST /users/registration 200 21.490 ms - 422
Error: Failed to save user for unknown reasons
    at router.route.get.post (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/users/index.js:42:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/response.js:267:15)
    at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/index.js:108:17
    at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
    at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
    at Layer.handle_error (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/layer.js:73:5)
    at trim_prefix (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:315:13)
    at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:335:12)
    at Immediate.next (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:275:10)
    at Immediate.<anonymous> (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/express/lib/router/index.js:635:15)
    at runCallback (timers.js:706:11)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
5
6
(node:68936) UnhandledPromiseRejectionWarning: E-mail already in use
(node:68936) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:68936) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
^C
xienkqul

xienkqul1#

错误“错误[ERR_HTTP_HEADERS_SENT]:无法在将标头发送到客户端后设置标头“意味着res.send/json/redirect在请求过程中触发了多次。乍一看,此代码块可能会导致此错误。

.get(function(req, res) {
        UserModel.find({}, (err, users) => {
            if (err) res.status(500).send(err)
            res.json(users)
        })
    })

在不查看发出的确切请求的情况下,我建议将console.log行放在各处,以查看是否可以查明运行时发生了什么。

更新

.get(function(req, res) {
            UserModel.find({}, (err, users) => {
                // If there's an error, this will fire and continue
                if (err) res.status(500).send(err) 

                // This fires next even if there is an error
                res.json(users)
            })
        })

这是可能导致该问题的原因之一。可能会引发两次res。修复方法是添加return。这可以确保代码不会继续。

.get(function(req, res) {
            UserModel.find({}, (err, users) => {                    
                if (err) return res.status(500).send(err)
                return res.json(users)
            })
        })

如果这样做不能解决问题,我建议在所有参数后面都加上console.log语句,这样您就可以精确地确定是哪一行出错了。例如:

router
    .route('/registration')
    .get(function(req, res) {
        console.log(0)
        UserModel.find({}, (err, users) => {
          console.log(1)
          if (err) res.status(500).send(err)
          console.log(2)
          res.json(users)
          console.log(3)
        })
    })
    .post(body('username').custom(value => {
        console.log(4)
        UserModel.findOne({ 'email': value }).then(user => {
            console.log(5)
            if (user) {
                console.log(6)
                return Promise.reject('E-mail already in use');
            }
        });
    }), async(req, res, next) => {
        console.log(7)
        try {
            let newUser = new UserModel(req.body)

            let savedUser = await newUser.save(err => {
                if (err) return res.json({ success: false, error: err })
                console.log(8)
                return res.json({ success: true })
            })
            console.log(9)
            if (savedUser) return res.redirect('/users/registration?success=true');
            console.log(10)
            return next(new Error('Failed to save user for unknown reasons'))

        } catch (err) {
            return next(err)
        }

    })

更新2

最后,我把代码放到编辑器中,注意到您没有在验证器中返回您的承诺,这可能是您遇到所有异步操作的原因。我添加了注解,向您显示我在哪里返回了承诺。希望这对您现在有用:)

router.route('/registration')
    .get(function(req, res) {
        UserModel.find({}, (err, users) => {
            if (err) res.status(500).send(err)
            res.json(users)
        })
    })
    .post(body('username').custom(value => {      
        return UserModel.findOne({ 'email': value }).then(user => { // Return Promise
          if (user) {
              return Promise.reject('E-mail already in use');
          }
        });
    }), async(req, res, next) => {
        try {
            let newUser = new UserModel(req.body)
            let savedUser = await newUser.save(err => {
              if (err) 
                return res.json({ success: false, error: err })
              return res.json({ success: true })
            })

            if (savedUser)
              return res.redirect('/users/registration?success=true');

            return next(new Error('Failed to save user for unknown reasons'))
        } catch (err) {
            return next(err)
        }
    })

module.exports = router
iswrvxsc

iswrvxsc2#

显式地返回API响应。因此,不要简单地说res.json(users),而是将其改为return res.json(users)

ejk8hzay

ejk8hzay3#

因此如果使用switch case,请使用***break或return***

相关问题