Node.js 服务器不允许发布请求

时间:2021-02-26 09:54:19

标签: node.js mongodb url-routing


我是 Node.js 的新手,试图创建一个简单的服务器来注册、登录并允许您获取用户列表。我还没有设置前端,通过邮递员或手动(作为硬编码)发送请求。
尝试发送发布请求(登录和注册)时出现奇怪的错误,另一方面,获取请求正常工作。

尝试通过邮递员发送请求时得到的结果(第一次成功,然后我开始收到此错误): MongoError: E11000 duplicate key error collection: usersBD.users index: username_1 dup key: { username: null } at Function.create (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\core\error.js:57:12) at toError (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\utils.js:123:22) at C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\operations\common_functions.js:265:39 at handler (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\core\sdam\topology.js:942:24) at C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\cmap\connection_pool.js:350:13 at handleOperationResult (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\core\sdam\server.js:558:5) at MessageStream.messageHandler (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\cmap\connection.js:277:5) at MessageStream.emit (events.js:315:20) at processIncomingData (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\cmap\message_stream.js:144:12) at MessageStream._write (C:\dev\Angular assigments\node-server-ivan\node_modules\mongodb\lib\cmap\message_stream.js:42:5) at writeOrBuffer (internal/streams/writable.js:358:12) at MessageStream.Writable.write (internal/streams/writable.js:303:10) at TLSSocket.ondata (internal/streams/readable.js:719:22) at TLSSocket.emit (events.js:315:20) at addChunk (internal/streams/readable.js:309:12) at readableAddChunk (internal/streams/readable.js:284:9) { driver: true, index: 0, code: 11000, keyPattern: { username: 1 }, keyValue: { username: null } }

也在浏览器中,当我将 URL 从 http://localhost:5000 更改为 http://localhost:5000/loginhttp://localhost:5000/reg 时,我收到此错误,这也很奇怪,因为昨天我收到了 console.log 并且一切正常正确。
reg:1 GET http://localhost:5000/reg 404 (Not Found)。 当我执行 http://localhost:5000/users 时,我得到 res.json 并且一切正常。 我确实理解 Mongo 错误是因为我的用户模型有问题。 但据我所知,当我只在搜索栏中添加一个 URL 时,它不应该导致错误。 我的 index.js

const express = require('express');
const mongoose = require('mongoose');
const authRouter = require('./authRouter')//yes
const PORT = process.env.PORT || 5000;
const connectionString = 'mongodb+srv://Ivan:aldaron1@cluster0.fivve.mongodb.net/usersBD?retryWrites=true&w=majority'//yes
const app = express();
app.use(express.json());
app.use(authRouter);
const start = async () => {
    try {
        await mongoose.connect(connectionString, {
            useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true
        })
        app.listen(PORT, () => console.log(`server started on port ${PORT}`))
    } catch (error) {
        console.log(error)
    }
}

start()

我的路由器:

const Router = require('express')
const router = new Router()
//const controller = require('./authController')
const User = require('./models/User');
const Role = require('./models/Role');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
const { check, validationResult } = require('express-validator')
const { config } = "./config"
router.post('/reg',
    [
        check('email', `Username can't be empty`).isEmail(), //isEmail()
        check('password', `Password supposed to be in range from 4 to 20`).isLength({ min: 4, max: 20 })
    ],
    async (req, res) => {// req-request from user,res- response to user
        try {
            const errors = validationResult(req)
            if (!errors.isEmpty()) {
                return res.status(400).json({ message: `Registration wasn't finished, please try again`, errors: errors.array() })
            }
            const { email, password } = req.body//user requesting it from server
            const candidate = await User.findOne({ email })
            if (candidate) {
                return res.status(400).json({ message: "User with this email is already registered" })
            }
            const hashPassword = await bcrypt.hashSync(password, 9);
            const userRole = await Role.findOne({ value: "User" });
            const user = new User({ email, password: hashPassword });
            await user.save()
            console.log("REG")//
            return res.status(201).json({ message: "User was succesfully registered" })
        } catch (e) {
            console.log(e)
            res.status(400).json({ message: 'Registration error' })
        }
    }
)
router.post('/login',
    [
        check('email', `Please in put a coorect email`).normalizeEmail().isEmail(), //isEmail()
        check('password', `Password supposed to be in range from 4 to 20`).isLength({ min: 4, max: 20 })
    ]//for password maybe exists

    , async (req, res) => {
        try {
            const errors = validationResult(req)
            if (!errors.isEmpty()) {
                return res.status(400).json({ message: `Log in unseccussfull, please try again`, errors: errors.array() })
            }
            const { email, password } = req.body;
            const user = await User.findOne({ email })
            if (!user) {
                return res.status(400).json({ message: `Username ${email} wasn't found` })
            }
            const validPassword = await bcrypt.compareSync(password, user.password) //-checking up user password
            if (!validPassword) {
                return res.status(400).json({ message: `Password isn't correct, please try again` })
            }
            const token = jwt.sign(
                { userId: user.id },
                config.get('jwtSecret'),
                { expiresIn: '1h' }
            );//fixed _id mongo shows in that way, that unchangable

            console.log("LOG")
            return res.json({ token, userId: user.id })//res.json возвращает на клиент сообщение

        } catch (e) {
            console.log(e)
            res.status(400).json({ message: 'Login error' })
        }

    })
router.get('/users', async (req, res) => {//endpoints - probably later add "auth/"
    try {
        //instead of making inpoint we are creating them manually (for now)
        //const userRole = new Role();
        //const adminRole = new Role({ value: 'Admin' })
        //await userRole.save();//saving them to database
        //await adminRole.save();
        res.json("user displaying works")
        console.log("USERS")
    } catch (e) { }
})  // add authController as a callback and not as a method from another object 26.07
//router.post('/login',)
//router.get('/users', controller.getUsers)




//read about difference beetween hash/hashSync, compare, compareSync
module.exports = router

我的用户模型:

const { Schema, model } = require('mongoose');


//Schema described how user will be stored in database
const User = new Schema({
    email: { type: String, unique: true, index: true, required: true },//email
    password: { type: String, required: true },
    roles: [{ type: String, ref: 'Role' }],
    //links:[{type:Types.ObjectId}] -- also add Types for import from mongoose
});

module.exports = model('User', User)// name and Schema

先谢谢你!

1 个答案:

答案 0 :(得分:0)

这个:MongoError:E11000重复键错误集合

表示已经有一个为 null 的用户名,所以我认为您之前尝试过注册,但由于某些原因,您的应用程序未读取该值。尝试删除您的收藏并重新注册。或者检查用户集合是否存在值为null的用户并删除。

注意:请编辑您的问题以使其具有最小的可重现性