javascript 找不到节点js路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28566487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:11:36  来源:igfitidea点击:

node js route not found

javascriptnode.js

提问by Marc Rasmussen

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: '[email protected]'
        };

        return dbUserObj;
    },

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

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

回答by HeadCode

Try moving your app.use(bodyParser…) statements above the login route. The order of middleware matters. At the time login is called the req object hasn't run through the bodyParser middleware yet.

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

Also, your router instance is mounted at "/api" so the router methods will never get called for "/login". The following line should be place above your 404 catchall:

此外,您的路由器实例安装在“/api”处,因此永远不会为“/login”调用路由器方法。下面这行应该放在你的 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'. Also, you had place the 'use' statement too far down.

之前,你使用过 app.use('/api', router),这意味着你的路由器路由只会被查看以 '/api' 开头的任何请求。此外,您将“使用”语句放得太低了。

回答by Yuri Zarubin

When setting up middleware, the order in which you call app.use() is key. In your server.js, you're setting up your application routes before you set up body parser. 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() 的顺序是关键。在您的 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
}));