mongoose 应用程序因重复响应而崩溃,未捕获错误

sqserrrh  于 2023-01-26  发布在  Go
关注(0)|答案(1)|浏览(145)

我需要添加一个用户我创建了这个Auth.js文件,同时从thundreclient命中此端点错误必须我捕获,必须发送res.json这是不会发生的,我应该怎么做:
Auth.js

const express=require('express');
const User = require('../models/User');
const router=express.Router();
const { body, validationResult } = require('express-validator');

router.post('/',[
        body('email').isEmail(),
        body('name').isLength({ min: 5 }),
        body('password').isLength({ min: 5 })
], async (req, res)=>{
        try{
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(400).json({ errors: errors.array() });
        }
      
        User.create({
                name: req.body.name,
                password: req.body.password,
                email: req.body.email
              }).then(user => res.json(user));
        
        }
        catch(errors) { 
                console.error(errors)
                res.json({error:'Please Use A Unique Value'})
        }

        

})

module.exports = router
g6ll5ycj

g6ll5ycj1#

因为你没有在路由器中进行异步操作,express忽略了从你的router.post方法返回的错误,因为它被当作一个承诺。
您需要删除async关键字并使您的路线同步:

const express=require('express');
const User = require('../models/User');
const router=express.Router();
const { body, validationResult } = require('express-validator');

router.post('/',[
        body('email').isEmail(),
        body('name').isLength({ min: 5 }),
        body('password').isLength({ min: 5 })
], (req, res)=>{  // removed async keyword
        try{
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(400).json({ errors: errors.array() });
        }
      
        User.create({
                name: req.body.name,
                password: req.body.password,
                email: req.body.email
              }).then(user => res.json(user));
        
        }
        catch(errors) { 
                console.error(errors)
                res.json({error:'Please Use A Unique Value'})
        }

        

})

相关问题