我正在尝试为我的应用创建用户数据库。我使用了与其他路线相同的代码,但似乎工作正常,但由于某些原因,当我尝试创建新用户时,我不断收到邮递员的404错误。我仍在学习js,所以这可能是一个愚蠢的错误,但是我无法弄清楚自己在做什么错。这是我的代码,非常感谢您的帮助!
users.js(路线):
const _ = require('lodash')
const {User, validate} = require('../models/user')
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({email: req.body.email});
if (user) return res.status(400).send('User already registered')
user = new User(_.pick(req.body,['name', 'email', 'password']))
await user.save();
res.send(_.pick(user, ['_id','name', 'email'])); });
module.exports = router;
user.js(模型)
const Joi = require('joi');
const mongoose = require('mongoose');
const User = mongoose.model('User', new mongoose.Schema({
name: {type: String, required: true, minlength: 5, maxlength: 50},
email: {type: String, required: true, minlength: 5, maxlength: 255, unique: true},
password: {type: String, required: true, minlength: 5, maxlength: 1024} }))
function validateUser(user) {
const schema = {
name: Joi.string().min(5).max(50).required(),
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required()
};
return Joi.validate(user, schema); }
exports.User = User; exports.validate = validateUser;
index.js:
const Joi = require('joi') Joi.objectId = require('joi-objectid')(Joi) const mongoose = require("mongoose")
const express = require("express");
const app = express();
const genres = require("./routes/genres");
const customers = require("./routes/customers")
const movies = require("./routes/movies")
const rentals = require("./routes/rentals")
const users = require("./routes/users")
mongoose.connect("mongodb://localhost/vidly")
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.log("Could not connect to MongoDB"))
app.use(express.json());
app.use("/api/genres", genres);
app.use("/api/customers", customers);
app.use("/api/movies", movies);
app.use("/api/rentals", rentals);
app.use("api/users", users)
const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Listening on port ${port}...`));