【问题标题】:NodeJS 404 ErrorNodeJS 404 错误
【发布时间】:2016-10-24 09:41:40
【问题描述】:

我正在尝试创建一个将检查用户凭据的中间件,如果成功,则使用用户信息创建一个 JWT。我想创建一个 cookie,然后将 JWT 存储在 cookie 中,但我似乎无法让它正常工作。在 post 上点击登录方法后,我收到 404 'Not Found' 错误,说它“Cannot POST /authenticate”。我错过了什么?

路线:

app.post('/authenticate', function(req, res, next){
    middleware.login(req, res, next);
});

中间件:

exports.login = function(req, res, next){
    var username = req.body.username;
    var password = req.body.password;
    User.findByUsername(username,function(err, user){
        if(err){
            res.send({ success: false, message: 'Authentication failed.' });
        }
        if (!user) {
            res.send({ success: false, message: 'Authentication failed. User not found.' });
        }
        if(user && !user.isuserenabled){
            res.send({ success: false, message: 'Authentication failed. User not found.' });
        }
        if (!UserSchema.comparePassword(password,user.user_password )) {
            res.send({ success: false, message: 'Authentication failed. User not found.' });
        }
        res.cookie('yummyCookie', jwt.sign(
            //payload, secret, options, [callback]
            {
                id: user.user_id,
                email: user.email,
                name: user.firstname + " " + user.lastname,
                role: user.role
            },
            config.secret, // DO NOT KEEP YOUR SECRET IN THE CODE
            {expiresIn: "1h"}, {secure: true, httpOnly: true}));
        return next();
    });
};

【问题讨论】:

    标签: javascript node.js express cookies http-headers


    【解决方案1】:

    您收到404 not found 的原因是因为您实际上没有发送任何响应,而只是将执行传递给下一个处理程序。因为在 express 返回 404 之后没有匹配的处理程序。 实际上调用了app.post,但是当您调用next() 时,它期望另一个中间件来处理请求。这是一个非常基本的示例,您的路由实际上被调用,但执行被传递给责任链中的下一个中间件。因为没有 - 您收到错误。

    var express = require('express');
    
    var app = express();
    
    app.post('/test', (req, res, next) => {
    	console.log('called');
    	next();
    });
    
    app.listen(5000);

    这会将“调用”写入控制台,但仍返回 404。您可以做的是在成功验证后添加另一个处理程序,如下所示:

    app.post('/authenticate', (req, res, next) => {
        res.send('OK').end();
    });

    或者您可以将该登录名合并到中间件本身中,而不是调用next()

    【讨论】:

    • 最后是否必须发送一些东西(在这种情况下,'OK')或者我可以调用 res.end(); ?
    • 你可以直接调用res.end(),它会返回一个空的body,HTTP状态为200
    猜你喜欢
    • 2013-07-18
    • 2020-12-06
    • 2017-11-21
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2018-07-28
    相关资源
    最近更新 更多