javascript - 找不到 Node js路由

标签 javascript node.js

我有以下方法来授权我的用户:

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');
router.post('/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);
});

还有我的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;

此服务器在端口 8080 上运行。

所以当我尝试去 http://localhost:8080/login我收到以下错误消息:

    Error: Not Found
   at app.use.bodyParser.urlencoded.extended (/var/www/example/backend/server.js:34:15)
   at Layer.handle [as handle_request] (/var/www/example/backend/node_modules/express/lib/router/layer.js:82:5)
   at trim_prefix (/var/www/example/backend/node_modules/express/lib/router/index.js:302:13)
   at /var/www/example/backend/node_modules/express/lib/router/index.js:270:7
   at Function.proto.process_params (/var/www/example/backend/node_modules/express/lib/router/index.js:321:12)
   at next (/var/www/example/backend/node_modules/express/lib/router/index.js:261:10)
   at next (/var/www/example/backend/node_modules/express/lib/router/route.js:100:14)
   at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
   at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
   at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)

然而,我的授权的其余部分似乎在工作,因为如果我去:

http://localhost:8080/api/user

我得到:{"status":401,"message":"Invalid Token or Key"}

谁能告诉我为什么我的登录不起作用?

完整服务器脚本:

    // 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');
router.post('/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('/api', 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);

最佳答案

尝试将您的 app.use(bodyParser…) 语句移动到登录路由上方。中间件的顺序很重要。在调用 login 时,req 对象还没有通过 bodyParser 中间件运行。

此外,您的路由器实例安装在“/api”,因此路由器方法永远不会被“/login”调用。下面这行应该放在你的 404 catchall 上面:

app.use('/', router);

之前,您使用过 app.use('/api', router),这意味着您的路由器路由只会针对任何以 '/api' 开头的请求进行查看。此外,您将“使用”声明放在太低的位置。

关于javascript - 找不到 Node js路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566487/

相关文章:

javascript - 防止将属性添加到 JavaScript 对象

javascript - 如何在键入时修改输入并让 Blazor 看到更改

javascript - 为 JSON 属性抛出 Nan 消息

node.js - Dockerized Node js 应用程序无法启动

javascript - “require”关键字在 Node Red Function Node 中不起作用

javascript - JQuery Focus/Blur 和非 Jquery Focus/blur 在 IE 11 (Internet explorer 11) 上不起作用

javascript - Action 必须是普通对象。尝试将 Action 分派(dispatch)为 redux 形式

javascript - AmCharts 内联代码 Uncaught ReferenceError

javascript - AngularJS + NodeJS 路由 - 不起作用

javascript - 如何修复 bookshelfjs 事务中的嵌套结构