导入后ExpressJs中间件不起作用

时间:2018-10-05 10:29:39

标签: javascript node.js express middleware

这是我的app.js

import path from 'path';
import bodyParser from 'body-parser';
import express from 'express';

import defender from 'inflex-defend-api';

import { key, secret } from './config/app';

let apiDefender = defender(key, secret);

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static('public'))

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(apiDefender.defend(false));

export default app;

尝试将此app.js导入server.js

import app from './app';

app.use('/v1.0', function (req, res, next) {
    console.log('Request Type:', req.method)
    //next()
});

如果我在server.js中使用'/v1.0'中间件,则不起作用,但是如果我在app.js中使用,则很好。

如果我不在路由中定义中间件,该如何在app.js中使用中间件。

例如(我不想要):

app.post('/v1.0/api/ahri', function (req, res, next) { 
   console.log('Request Type:', req.method); 
   next(); 
}, function (req, res, next) {
   console.log('I know the request type');
}); 

1 个答案:

答案 0 :(得分:1)

与其尝试在server.js中使用app.js(我假设这是您的js,您在其中定义了所有其余的映射),而是在app.js中使用server.js

app.js

import path from 'path';
import bodyParser from 'body-parser';
import express from 'express';

import defender from 'inflex-defend-api';

import { key, secret } from './config/app';

let apiDefender = defender(key, secret);

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static('public'))

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(apiDefender.defend(false));

require('./server)(app);

export default app;

server.js

module.exports = (app) => {
    app.use('/v1.0', function (req, res, next) {
        console.log('Request Type:', req.method)
        //next()
    });
}