简体   繁体   English

找不到节点js路由

[英]node js route not found

i have the following method to auth my users:我有以下方法来验证我的用户:

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

And my Auth.js还有我的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;

This server runs on port 8080.该服务器在端口 8080 上运行。

So when i attempt to go to http://localhost:8080/login i get the following error message:因此,当我尝试访问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)

However it seems that the rest of my auth is working because if i go to:但是,我的其余身份验证似乎正在工作,因为如果我去:

http://localhost:8080/api/user

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

Can anyone tell me why my login does not work?谁能告诉我为什么我的登录不起作用?

Full server script:完整的服务器脚本:

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

Try moving your app.use(bodyParser…) statements above the login route.尝试将您的 app.use(bodyParser...) 语句移到登录路径上方。 The order of middleware matters.中间件的顺序很重要。 At the time login is called the req object hasn't run through the bodyParser middleware yet.在调用 login 时,req 对象还没有通过 bodyParser 中间件。

Also, your router instance is mounted at "/api" so the router methods will never get called for "/login".此外,您的路由器实例安装在“/api”处,因此永远不会为“/login”调用路由器方法。 The following line should be place above your 404 catchall:下面这行应该放在你的 404 catchall 之上:

app.use('/', router);

Before, you had used app.use('/api', router), which means that your router routes will only be looked at for any request that starts with '/api'.之前,你使用过 app.use('/api', router),这意味着你的路由器路由只会被查看以 '/api' 开头的任何请求。 Also, you had place the 'use' statement too far down.此外,您将“使用”语句放得太低了。

When setting up middleware, the order in which you call app.use() is key.设置中间件时,调用 app.use() 的顺序是关键。 In your server.js, you're setting up your application routes before you set up body parser.在您的 server.js 中,您在设置正文解析器之前设置了应用程序路由。 Meaning, when the request comes in, is is not parsed before hitting your application logic.意思是,当请求进来时,在命中您的应用程序逻辑之前不会被解析。 You need to move the app.use(bodyParser) parts to the top of your code.您需要将 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
}));

perphaps you have to move the也许你必须移动

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

to the bottom of your code, but before "app.listen()", The order you declare the routes in the router are important, so putting the "app.use" after you declare all theses routes, would search a match with all the previous route and if none is found then it will enter in that last one到代码底部,但在“app.listen()”之前,您在路由器中声明路由的顺序很重要,因此在声明所有这些路由之后放置“app.use”,将搜索所有匹配项上一条路线,如果没有找到,则进入最后一条路线

Like this:像这样:

.
..
...
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