Expressjs:无法在Postman中执行POST /api/v1/users/

cx6n0qe3  于 2022-11-07  发布在  Postman
关注(0)|答案(1)|浏览(239)

我正在测试我们在Express中开发的一个API。而且应用程序似乎开始时运行良好。但是当我测试用户的API时,它返回了许多错误消息:
这是我的模型
User.js

const mongoose = require('mongoose');

    const userSchema = mongoose.Schema({
        name: {
            type: String,
            required: true,
            min: 6,
            max: 255
        },
        email: {
            type: String,
            required: true,
            min: 6,
            max: 1024
        },
        password: {
            type: String,
            required: true,
            minlength: 6
        },
        subscribe: {
            type: Boolean,
            default: false
        },    
        date: {
            type: Date,
            default: Date.now
        },
        role: {
            type: String,
            required: false,
            minlength: 4
        },
        address: {
            type: String,
            required: false,
            minlength: 4,
            defaultValue: ""
        },        
        nonce: {
            type: String,
            required: false,
            minlength: 4,
            defaultValue: ""
        },            
    })

    module.exports = mongoose.model('User', userSchema);

这是我的控制器(user.js):

const Joi = require('@hapi/joi');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const nodemailer = require("nodemailer");

//models
const User = require('../models/user');
const expired_token = require('../models/expired_token');

module.exports = {

    register: async (req, res) => {

        const schemaRegister = Joi.object({
            name: Joi.string().min(3).max(255).required(),
            email: Joi.string().min(4).max(255).required().email(),
            password: Joi.string().min(6).max(1024).required()
        })

        // validate user
        const { error } = schemaRegister.validate(req.body)

        if (error) {
            return res.status(400).json({
                data: error,
                message: error.details[0].message,
                status: "error"
            })
        }

        const isEmailExist = await User.findOne({ email: req.body.email });
        if (isEmailExist) {
            return res.status(400).json({
                data: "",
                message: "email already registered",
                status: "error"
            })
        }    

        // hash password
        const salt = await bcrypt.genSalt(10);
        const password = await bcrypt.hash(req.body.password, salt);

        const user = new User({
            name: req.body.name,
            email: req.body.email,
            role: "user",
            password: password
        });

        try {

            const savedUser = await user.save();

            console.log(savedUser);

            const token = jwt.sign({
                name: savedUser.name,
                id: savedUser._id,
                email: savedUser.email,
                role: savedUser.role
            }, process.env.TOKEN_SECRET);

            res.status(200).json({ 
                data: {
                    email:savedUser.email,
                    name: savedUser.name,
                    role: savedUser.role,
                    token: token
                },
                message:"Successful request",
                status: "success"
            });     

        } catch (error) {
            res.status(401).json({ 
                data: error,
                message:"Error creating user",
                status: "error"
            });
        }        
    },

    login: async (req, res) => {    

        const schemaLogin = Joi.object({
            email: Joi.string().min(6).max(255).required().email(),
            password: Joi.string().min(6).max(1024).required()
        })

        const { error } = schemaLogin.validate(req.body);
        if (error) {
            return res.status(400).json({
                data: error,
                message: error.details[0].message,
                status: "error"
            })
        }

        const user = await User.findOne({ email: req.body.email });
        if (!user) {
            return res.status(400).json({
                data: "",
                message: "User not found",
                status: "error"
            })
        }   

        const validPassword = await bcrypt.compare(req.body.password, user.password);
        if (!validPassword) {
            return res.status(400).json({
                data: {},
                message: "Invalid password",
                status: "error"
            })
        }    

        const token = jwt.sign({
            name: user.name,
            id: user._id,
            email: user.email,
            role: user.role
        }, process.env.TOKEN_SECRET);

        res.status(200).json({ 
            data: {
                email:user.email,
                name: user.name,
                token: token
            },
            message:"Successful request",
            status: "success"
        });     
    },    

    list_users: async (req, res) => {

        const users = await User.find({});

        res.status(200).json({ 
            data: users,
            message:"Successful request",
            status: "success"
        });   
    },

    logout: async (req, res) => {

        let user_info = req.decoded;
        let token = req.token; 

        const expired_token_exists = await expired_token.findOne({ token: token });
        if (expired_token_exists) {
            return res.status(200).json({
                data: "",
                message: "user already logged out",
                status: "success"
            })
        } 

        const data = new expired_token({
            id_user: user_info.id,
            token: token
        });

        try {
            const saved_expired_token = await data.save();
            res.status(200).json({ 
                data: saved_expired_token,
                message:"Successful request",
                status: "success"
            });     
        } catch (error) {
            res.status(401).json({ 
                data: error,
                message:"Error creating user",
                status: "error"
            });
        }        

    },  

    get_user_data: async (req, res) => {
        let user_info = req.decoded;
        try {
            const user = await User.find({
                _id:user_info.id
            });
            const user_json=user[0];
            const user_data = {
                id:user_info.id,
                name:user_json.name,
                email:user_json.email,
                subscribe:user_json.subscribe,
                role:user_json.role,
                date:user_json.date
            };
            res.status(200).json({ 
                data: user_data,
                message:"Successful request",
                status: "success"
            }); 
        } catch (error) {
            res.status(401).json({ 
                data: error,
                message:"Error getting user data",
                status: "error"
            });
        }
    }

}

这是我的路线(index.js):

const { func } = require('@hapi/joi');
const controller = require('../../v1/controllers/users');
const verifyToken = require('../../v1/utils').verifyToken;

module.exports = (router) => {

    router.route('/list_users')
        .get(verifyToken, controller.list_users);

    router.route('/register')
        .post(controller.register);

    router.route('/login')
        .post(controller.login);

    router.route('/logout')
        .post(verifyToken, controller.logout);

    router.route('/get_user_data')
        .get(verifyToken, controller.get_user_data);

    return router;
}

当然还有我的索引文件(index.js):

let users = require('./v1/routes/users.js');
app.users('/api/v1/users', users(router));

但是,当我尝试在Postman中获取类型为http://localhost:3000/api/v1/users的POST请求时,结果是Cannot POST /api/v1/users

这是什么原因呢?

mwngjboj

mwngjboj1#

您需要在任何路由中添加/api/v1/
就像这样

module.exports = (router) => {

router.route('/api/v1/list_users')
    .get(verifyToken, controller.list_users);

router.route('/api/v1/register')
    .post(controller.register);

router.route('/api/v1/login')
    .post(controller.login);

router.route('/api/v1/logout')
    .post(verifyToken, controller.logout);

router.route('/api/v1/get_user_data')
    .get(verifyToken, controller.get_user_data);

return router;

}

和其他事情,您需要为用户创建路由。
我在github中使用express创建了一个简单的restful api,您可以在此存储库中看到任何创建路由的示例。
Github Repo

相关问题