【问题标题】:NodeJS & MongoDB. POST Request gets 404 codeNodeJS 和 MongoDB。 POST 请求得到 404 码
【发布时间】:2019-12-26 02:47:47
【问题描述】:

当我尝试发送 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/users.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

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

【问题讨论】:

    标签: javascript node.js mongodb express routes


    【解决方案1】:

    您的路线是正确的。仅当找不到路由时才会出现错误 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) => {
    

    【讨论】:

    • 谢谢,对我帮助很大;)
    【解决方案2】:

    我不知道,但从第一个角度来看,我认为您在路线之前缺少破折号

    router.get('signin', (req, res) => {  // '/singin'
        res.render('signin');
    });
    
    router.post('signin', (req, res, next) => {  // '/singin'
        passport.authenticate('local', {
            successRedirect:'profile',
            failureRedirect:'signin',
            failureFlash: true
        })(req, res, next);
    });
    
    router.get('logout', (req, res) => { // '/logout'
        res.render('logout');
        req.flash('success', 'You are logged out');
        res.redirect('signin');
    });
    

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多