gpt4 book ai didi

node.js - POST 请求中的输入无效

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:56 24 4
gpt4 key购买 nike

我在 Postman 上的注册 POST 请求中收到无效输入错误。我已经检查了我的用户模型属性,但似乎无法准确找到哪些输入被称为无效。这是我的模型、 Controller 、路线。和应用程序.js。请看一下。

应用程序

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const usersRoutes = require('./routes/users-routes');
const postsRoutes = require('./routes/posts-routes');
const HttpError = require('./models/http-error');
const app = express();

app.use(bodyParser.json());

app.use('/api/users', usersRoutes);
app.use('/api/posts', postsRoutes);

app.use((req, res, next) => {
const error = new HttpError('Could not find this route.', 404);
throw error;
})

app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500)
res.json({ message: error.message || 'An unknown error occurred!' });
});

const connectUrl = 'hidden';

const connectConfig = {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}

mongoose
.connect(connectUrl, connectConfig)
.then(() => {
app.listen(5000);
})
.catch(err => {
console.log(err);
});

用户模型

const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
avatarUrl: { type: String, required: true },
posts: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Post' }]
});

用户 Controller

const signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { username, email, password } = req.body;


let existingUser
try {
existingUser = await User.findOne({ email: email })
} catch (err) {
const error = new HttpError('Signing up failed, please try again later.', 500);
return next(error);
}

if (existingUser) {
const error = new HttpError('User exists already, please login instead.', 422);
return next(error);
}

const createdUser = new User({
username,
email,
password,
avatarUrl: 'https://images.pexels.com/photos/406014/pexels-photo-406014.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260',
posts: []
});

try {
await createdUser.save();
} catch (err) {
const error = new HttpError('Signup failed, please try again.', 500);
return next(error);
}

res.status(201).json({ user: createdUser.toObject({ getters: true })});
}

用户路线

router.post(
'/signup',
[
check('username').not().isEmpty(),
check('email').normalizeEmail().isEmail(),
check('password').isLength({ min: 6 })
],
usersController.signup
);

postman

enter image description here

最佳答案

确保在中间件中使用body parser:

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

关于node.js - POST 请求中的输入无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com