Nodejs中间件总是被执行

时间:2018-02-21 10:27:09

标签: node.js

我正在学习NodeJS,我无法理解为什么我的中间件总是被执行。 根据我的理解,我编写的中间件应该在中间件本身之后声明的所有路由上执行。

我的index.js是这样的:

const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const bodyParser = require('body-parser'); // Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

const configdb = require('./config/db_develop');
const path = require('path');

const authentication = require('./routes/authentication')(router); // Import Authentication Routes
const noNeedForAuth = require('./routes/noNeedForAuth')(router);


const app = express();
const port = 30000;

mongoose.Promise = global.Promise;
mongoose.connect(configdb.uri, (err) => {
  if (err) {
    console.log('Could not connect to database ' + err);
  } else {
    console.log('Connected to the database ' + configdb.db);
  }
});

app.use(bodyParser.urlencoded({
  extended: false
})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json

app.use(express.static(__dirname + '/frontend/buildpath'));

app.use('/noNeedForAuth', noNeedForAuth);
app.use('/users', authentication); 

app.get('*', (req, res) => {
  res.send(path.join(__dirname + '/client/dist'));
});

app.listen(port, () => {
  console.log('Listening on port ' + port + '!');
});

authentication.js是:

const User = require('../models/user'); // Import User Model Schema
const config = require('../config/db_develop.js'); // Import database configuration
const jwt = require('jsonwebtoken'); // Compact, URL-safe means of representing claims to be transferred between two parties.

module.exports = (router) => {

  router.post('/register', (req, res) => {
    //Register
  });
  router.post('/login', (req, res) => {
    //Login
  });

  // MIDDLEWARE
  router.use((req, res, next) => {
    const token = req.headers['authorization']; // Create token found in headers
    // Check if token was found in headers
    if (!token) {
      res.status(403);
      res.json({
        success: false,
        message: 'No token provided'
      }); // Return error
    } else {
      // Verify the token is valid
      jwt.verify(token, config.secret, (err, decoded) => {
        // Check if error is expired or invalid
        if (err) {
          res.json({
            success: false,
            message: 'Token invalid: ' + err
          }); // Return error for token validation
        } else {
          req.decoded = decoded; // Create global variable to use in any request beyond
          next(); // Exit middleware
        }
      });
    }
  });

  /* ===============================================================
     Route to get user's profile data
  =============================================================== */
  router.get('/profile', (req, res) => {
    //Profile, protected route
  });

  return router; // Return router object to main index.js
}

我的noNeedForAuth.js是

module.exports = (router) => {
  /* ===============================================================
     Route to get all sections' names
  =============================================================== */
  router.get('/something', (req, res) => {
    // Do something
        res.json({
          message: 'foobar'

    });
  });

  return router; // Return router object to main index.js
}

根据我的理解,应该在不传递中间件的情况下执行对/ noNeedForAuth / something的查询,因此无需身份验证。但这种情况并没有发生,中间件总是先执行。

我错过了什么? 感谢

1 个答案:

答案 0 :(得分:0)

您正在将中间件应用到路由器,而没有任何装载路径。它将在任何路线上执行。

尝试类似的东西:

// MIDDLEWARE
  router.use('/protected', (req, res, next) => {
    const token = req.headers['authorization']; // Create token found in headers
    // Check if token was found in headers
    if (!token) {
      res.status(403);
      res.json({
        success: false,
        message: 'No token provided'
      }); // Return error
    } else {
      // Verify the token is valid
      jwt.verify(token, config.secret, (err, decoded) => {
        // Check if error is expired or invalid
        if (err) {
          res.json({
            success: false,
            message: 'Token invalid: ' + err
          }); // Return error for token validation
        } else {
          req.decoded = decoded; // Create global variable to use in any request beyond
          next(); // Exit middleware
        }
      });
    }
  });

您所有路线,其中用户已被认证,是落后/protected