没有find节点js路由

我有以下方法来authentication我的用户:

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) 

但是,似乎我的身份validation的其余部分正在工作,因为如果我去:

 http://localhost:8080/api/user 

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

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

完整的服务器脚本

  // 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路线上方。 中间件的顺序很重要。 在login被调用的时候,req对象还没有通过bodyParser中间件运行。

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

 app.use('/', router); 

之前,您已经使用过app.use('/ api',router),这意味着您的路由器路由只会被查看任何以'/ api'开头的请求。 另外,你已经把“使用”语句放在了太远的地方。

设置中间件时,调用app.use()的顺序是关键。 在你的server.js中,你设置你的应用程序路由,然后你设置正文分析器。 这意味着当请求进入时,在命中您的应用程序逻辑之前不会被parsing。 您需要将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 }));