繁体   English   中英

找不到节点js路由

[英]node js route not found

我有以下方法来验证我的用户:

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' 开头的任何请求。 此外,您将“使用”语句放得太低了。

设置中间件时,调用 app.use() 的顺序是关键。 在您的 server.js 中,您在设置正文解析器之前设置了应用程序路由。 意思是,当请求进来时,在命中您的应用程序逻辑之前不会被解析。 您需要将 app.use(bodyParser) 部分移动到代码的顶部。

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
}));

也许你必须移动

app.use("/", (req, res, next) => {
  res.status("404").json({message: "Not found"})
})

到代码底部,但在“app.listen()”之前,您在路由器中声明路由的顺序很重要,因此在声明所有这些路由之后放置“app.use”,将搜索所有匹配项上一条路线,如果没有找到,则进入最后一条路线

像这样:

.
..
...
app.use('/api', router);
app.use(division_model);
app.use(user_model);
app.use(team_model);

app.use("/", (req, res, next) => {
  res.status("404").json({message: "Not found"})
})

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM