javascript - NodeJS 和 MongoDB。 POST 请求获取 404 代码

标签 javascript node.js mongodb express routes

当我尝试发送 POST 请求时,它返回 404,尽管所有路由都是正确的。

我翻遍了很多类似的问题,但没有找到任何似乎可以解决我的问题的东西。

这是一个代码:

App.js

const http = require('http');
const url = require('url');
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const passport = require('passport');

mongoose.connect('mongodb://localhost:27017/mydb');
let db = mongoose.connection;
db.once('open', () => {
    console.log('Connected to Database');
});
db.on('error', (err) => {
    console.log(err);
});

const server = express();
server.use(express.static('dist', { extensions: ['html'] }));

let users = require('./routes/users');
server.use(users);

server.use(function (req, res, next) {
    res.status(404).sendFile(path.join(__dirname+'/dist/404.html'));
});

const port = process.env.port || 3000;
server.listen(port, () => {
    console.log(`Server has been established on port ${port}`)
});

./models/user.js


const User = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    lastname: {
        type: String,
        required: true
    },
    login: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    b_day: {
        type: String,
        required: true
    },
    b_month: {
        type: String,
        required: true
    },
    b_year: {
        type: String,
        required: true
    },
    gender: {
        type: String,
        required: true
    }
});

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

./routes/user.js

const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');

let User = require('../models/user');
//Register Form
router.get('/signup', (req, res) => {
    console.log(res);
    res.render('signup');
});

//Register Process

router.post('signup', (req, res) => {
    const name = req.body.name;
    const lastname = req.body.lastname;
    const login = req.body.login;
    const password = req.body.password;
    const password2 = req.body.repeat_password;
    const b_day = req.body.b_day;
    const b_month = req.body.b_month;
    const b_year = req.body.b_year;
    const gender = req.body.gender;

    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('lastname', 'Lastname is required').notEmpty();
    req.checkBody('login', 'Login is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
    req.checkBody('b_day', 'Birth day is required').notEmpty();
    req.checkBody('b_month', 'Birth month is required').notEmpty();
    req.checkBody('b_year', 'Birth year is required').notEmpty();
    req.checkBody('gender', 'Gender is required').notEmpty();

    let errors = req.validationErrors();

    if(errors) {
        res.render('signup', {
            errors:errors
        });
    } else {
        let newUser = new User({
            name:name,
            lastname:lastname,
            login:login,
            password:password,
            gender:gender,
            b_day:b_day,
            b_month:b_month,
            b_year:b_year
        });

        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.password, salt, (err, hash) => {
                if(err) {
                    console.log(err);
                }
                newUser.password = hash;
                newUser.save((err) => {
                    if(err) {
                        console.log(err);
                        return;
                    } else {
                        req.flash('success', 'You are now registered');
                        res.redirect('signin');
                    }
                });
            });
        });
    }
});

router.get('signin', (req, res) => {
    res.render('signin');
});

router.post('signin', (req, res, next) => {
    passport.authenticate('local', {
        successRedirect:'profile',
        failureRedirect:'signin',
        failureFlash: true
    })(req, res, next);
});

router.get('logout', (req, res) => {
    res.render('logout');
    req.flash('success', 'You are logged out');
    res.redirect('signin');
});

module.exports = router;

还有项目结构

├── dist
├── routes
│   └── users.js
├── models
│   └── user.js
└── app.js

我希望它将处理注册表单中的所有数据,然后重定向到登录页面。

最佳答案

您的路线是正确的。仅当未找到路由时才会出现 404 错误。就您而言,发生这种情况是因为您在调用注册(发布请求)和登录路由以及 users.js 之前没有添加“/”。

现在你的 api url 变成这样:

localhost:3000/userssignin

应该是:

localhost:3000/users/signin

所以,你的路线应该是:

router.post('/signup', (req, res) => {

router.get('/signin', (req, res) => {

router.post('/signin', (req, res) => {

关于javascript - NodeJS 和 MongoDB。 POST 请求获取 404 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581188/

相关文章:

node.js - 使用 dwyl/aws-sdk-mock 模拟 AWS 不起作用

node.js - mongodb TypeError : client. db.collection 不是函数

javascript - Google Drive Realtime API 离线和同步支持

Javascript/jQuery 监视 CSS 更改

javascript - 使用 HTML5 Slider 调整 Div 的 scaleX 和 scaleY

javascript - 使用 dataTable.js Bootstrap 表排序、过滤、分页

javascript - 将变量传递给 Handlebars 上的每个响应

node.js - Mongoose - 如何在 Mongoose 中的填充字段数组中选择特定对象?

node.js - 在 Mongo 中,增量和返回值——可能在 1 个调用中?

node.js - 与 MongoDB 的单个连接还是多个连接更好?