node.js - Node.js 服务器不允许发出 post 请求
问题描述
我是 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
tohttp://localhost:5000/login
或http://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
先感谢您!
解决方案
这:MongoError:E11000重复键错误集合
意味着已经有一个为 null 的用户名,所以我认为您之前尝试过注册,但由于某种原因,您的应用程序没有读取该值。尝试删除您的收藏并重新注册。或者检查用户集合是否存在值为 null 的用户并将其删除。
注意:请编辑您的问题,使其成为最小可重复的问题
推荐阅读
- javascript - 从 DOM 标头资源中提取 HTML 链接(没有 ID 或类)
- sms - Twilio 如何分割包含 url 的长消息?
- javascript - Javascript 滚动侦听器在 chrome 或 firefox 中不起作用
- python - 将分类变量绘制为堆积条形图
- java - Java - 动态访问嵌套的 JSONArray 值
- java - 确定文件编码并打印变音符号
- webdriver - java.lang.IllegalStateException:在 Selenium 中配置 Firefox 浏览器时出错
- node.js - NodeJS 在 JSON 中遍历城市,返回每个城市的城市和用户
- json - jq:错误(在 ec-state:1028):无法迭代 null(null)
- influxdb - 如何将流中的当前值与 tickscript 中的先前值进行比较?