节点js发布认证req.username&密码未定义

时间:2015-02-18 00:47:07

标签: javascript node.js

因此,经过大约4个小时的努力,我终于完成了一些工作:P

现在我有一个问题是我用邮递员发送服务器的图片:

My postman

如果您无法从图片中看出我正在使用form-data发送

username = arvind@myapp.com

password = pass123

很标准。

结果是:

   {
    "status": 401,
    "message": "Invalid credentials"
   }

现在我的服务器看起来像这样:

Server.js

    // BASE SETUP
// =============================================================================
var express = require('express'),
    bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');

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

// =============================================================================

//Secure

app.all('/*', function(req, res, next) {
    // CORS headers
    res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    // Set custom headers for CORS
    res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
    if (req.method == 'OPTIONS') {
        res.status(200).end();
    } else {
        next();
    }
});

var auth = require('./auth.js');
app.all('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

var env = app.get('env') == 'development' ? 'dev' : app.get('env');
var port = process.env.PORT || 8080;

var Sequelize = require('sequelize');

// db config
var env = "dev";
var config = require('./database.json')[env];
var password = config.password ? config.password : null;

// initialize database connection
var sequelize = new Sequelize(
    config.database,
    config.user,
    config.password,
    {
        logging: console.log,
        define: {
            timestamps: false
        }
    }
);

//Init models
var division_model = require('./lb_models/division/division_model')(express,sequelize,router);
var user_model = require('./lb_models/user/user_model')(express,sequelize,router);
var team_model = require('./lb_models/Team')(express,sequelize,router);

app.use(division_model);
app.use(user_model);
app.use(team_model);

// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);

我的auth.js:

    var jwt = require('jwt-simple');

var auth = {
    login: function(req, res) {

        var username = req.body.username || '';
        var password = req.body.password || '';

        if (username == '' || password == '') {
            res.status(401);
            res.json({
                "status": 401,
                "message": "Invalid credentials"
            });
            return;
        }

        // Fire a query to your DB and check if the credentials are valid
        var dbUserObj = auth.validate(username, password);

        if (!dbUserObj)
        { // If authentication fails, we send a 401 back
            res.status(401);
            res.json({
                "status": 401,
                "message": "Invalid credentials"
            });
            return;
        }

        if (dbUserObj) {

            // If authentication is success, we will generate a token
            // and dispatch it to the client
            res.json(genToken(dbUserObj));
        }

    },

    validate: function(username, password) {
        // spoofing the DB response for simplicity
        var dbUserObj = { // spoofing a userobject from the DB.
            name: 'arvind',
            role: 'admin',
            username: 'arvind@myapp.com'
        };

        return dbUserObj;
    },

    validateUser: function(username) {
        // spoofing the DB response for simplicity
        var dbUserObj = { // spoofing a userobject from the DB.
            name: 'arvind',
            role: 'admin',
            username: 'arvind@myapp.com'
        };

        return dbUserObj;
    }
}

// private method
function genToken(user) {
    var expires = expiresIn(7); // 7 days
    var token = jwt.encode({
        exp: expires
    }, require('../config/secret')());

    return {
        token: token,
        expires: expires,
        user: user
    };
}

function expiresIn(numDays) {
    var dateObj = new Date();
    return dateObj.setDate(dateObj.getDate() + numDays);
}

module.exports = auth;

使用auth.js中第4行的调试器,我能够找到用户名和&密码未定义。 (因此变成空字符串)

谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:1)

尝试将标题作为Content-Type:application / json放在POSTMan中。