【问题标题】:Node js post authentication req.username & password is undefined节点 js 发布身份验证 req.username & password 未定义
【发布时间】:2015-02-18 10:18:24
【问题描述】:

所以在差不多 4 个小时之后,我终于打了一些电话来上班:P

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

如果你不能从图片中看出我正在使用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 行的调试器,我发现用户名和密码都未定义。 (因此变成了空字符串)

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

【问题讨论】:

  • 如果你发送form-data,你需要添加一个中间件来解析form-data,比如busboy或multiparty。您只启用了 json 和 urlencoded 正文解析。
  • @loganfsmyth 表单数据不是访问 api 的最常用方式吗?
  • 我会说这取决于 API。如今,JSON 可能是最受欢迎的。 form-data 主要用于传输二进制数据。

标签: javascript node.js


【解决方案1】:

尝试将 Header 作为 Content-Type: application/json 放入 POSTMan 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多