未定义的帖子体变量

时间:2016-03-30 05:21:47

标签: node.js express body-parser

我在NodeJS中有以下登录/注册API。到目前为止,除了登录路线之外的一切都正常每当我尝试使用现有的用户名和密码登录时,都会收到以下错误:

  

无法从未定义的

中读取属性'username$#39;

错误在此位置的api.js上触发:username: req.body.username

当我执行req.body的控制台日志时,我得到的输出是undefined也可能有所帮助。

下面是我的服务器和api javascript文件,我希望这些文件足以让您了解我的代码有什么问题。如果需要,我可以提供更多代码来找到解决方案。

FYI:我正在根据教程学习​​,所以请假设我对此事没有深入的了解。

server.js

var express =    require('express'),
    bodyParser = require('body-parser'),
    morgan =     require('morgan'),
    config =     require('./config'),
    mongoose =   require('mongoose'),
    app =        express();

mongoose.connect(config.database, function(err){
    if(err){
        console.log(err);
    }
    else {
        console.log('Connected to the database');
    }
});

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());
app.use(morgan('dev'));

// Front end API
app.use(express.static(__dirname + '/public'));

// Middleware API
var api = require('./app/routes/api')(app, express);
app.use('/api', api);

app.get('*', function(req, res){
    res.sendFile(__dirname + "/public/app/views/index.html");
});

app.listen(config.port, function(err){
    if(err){
        console.log(err);
    }
    else {
        console.log("Listening on port " + config.port);
    }
});

api.js

var User = require("../models/users"),
    Story = require("../models/story"),
    config = require("../../config"),
    secretKey = config.secretKey,
    jsonwebtoken = require("jsonwebtoken");

function createToken(user){
    var token = jsonwebtoken.sign({
        id: user._id,
        name: user.name,
        username: user.username
    }, secretKey, {
        expirationMinute: 1440
    });

    return token;
}

module.exports = function(app, express){
    var api = express.Router();

    api.post('/signup', function(req, res){
        var user = new User({
            name: req.param.name,
            username: req.body.username,
            password: req.body.password
        });

        user.save(function(err){
            if(err){
                res.send(err);
                return;
            }
            res.json({message: 'User has been created!'});
        });
    });

    api.get('/users', function(req, res){
        User.find({}, function(err, users){
            if(err){
                res.send(err);
                return;
            }
            res.json(users);
        });
    });

    api.post('/login', function(res, req){
        console.log(req.body);
        User.findOne({
            username: req.body.username
        }).select('password').exec(function(err, user){
            if(err){
                throw err;
            }
            if(!user){
                res.send({message: "User does not exist"});
            }
            else if(user){
                var validPassword = user.comparePassword(req.body.password);

                if(!validPassword){
                    res.send({
                        message:"Invalid Password"
                    });
                }
                else {
                    // Token
                    var token = createToken(user);

                    res.json({
                        success: true,
                        message: "Successful login",
                        token: token
                    });
                }
            }
        });
    });

    api.use(function(req, res, next){
        console.log("Somebody just came to our api");

        var token = req.body.token || req.param('token') || req.headers['x-access-token'];

        // check if does not exist
        if(token){
            jsonwebtoken.verify(token, superSecret, function(err, decoded){
                if(err){
                    res.status(403).send({
                        success: false,
                        message: "Failed to authenticate user"
                    });
                }
                else {
                    req.decoded = decoded;
                    next();
                }
            });
        }
        else {
            res.status(403).send({
                success: false,
                message: 'No token provided'
            });
        }
    });

    api.route('/')
        .post(function(req, res){
            var story = new Story({
                creator: req.decoded.id,
                content: req.body.content
            });

            story.save(function(err){
                if(err){
                    res.send(err);
                    return;
                }
                res.json({message: "New Story Created"});
            })
        })
        .get(function(req, res){
            Story.find({
                creator: req.decoded.id
            }, function(err, stories){
                if(err){
                    res.send(err);
                    return;
                }
                res.json(stories);
            });
        });

    api.get('/me', function(req, res){
        res.json(req.decoded);
    });

    return api;
}

1 个答案:

答案 0 :(得分:2)

api.post('/login', function(res, req){行中resreq发生逆转。

应该是:

api.post('/login', function(req, res) {
    ...
});