如何添加中间件来捕获快递上的所有成功请求?

时间:2018-04-16 10:27:40

标签: node.js express

我试图将我的api上的用户活动记录到mongo集合中。问题是,当我在路由上方添加中间件时,我可以记录请求。但那时中间件无法知道请求是成功还是失败。如果我在路线下方添加中间件,它就不会被调用。

现在我在每个路线功能的末尾运行import express from 'express'; import logger from 'morgan'; import bodyParser from 'body-parser'; import helmet from 'helmet'; import filter from 'content-filter'; import cors from 'cors'; import dotenv from 'dotenv'; import mongoose from 'mongoose'; import Raven from 'raven'; import { createFirebaseAuth } from 'express-firebase-auth'; import routes from './routes'; import { DB_CONFIG } from './config'; import firebase from './lib/firebase'; import permissions from './middleware/permissions'; import userLogs from './middleware/userLog'; // Setup environment config dotenv.config(); // Initiate the app const app = express(); // Connect to the database mongoose.connect(DB_CONFIG.uri, DB_CONFIG.options); mongoose.Promise = global.Promise; // Configure error reporting if (process.env.RAVEN_DSN) { Raven.config(process.env.RAVEN_DSN).install(); app.use(Raven.requestHandler()); } // Apply the middleware app.use(filter()); app.use(helmet.xssFilter()); app.use(helmet.hidePoweredBy()); app.use(helmet.noSniff()); app.use(cors()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(logger('dev')); // Add the firebase authenticatior const firebaseAuth = createFirebaseAuth({ firebase, checkEmailVerified: true, checkEmailVerifiedIgnoredUrls: ['/users', '/users/updatepassword'] }); app.use(firebaseAuth); // Add the permissions module app.use(permissions); // Add the routes app.use('/', routes); // Catch 404 and forward to error handler app.use((req, res, next) => { const err = new Error('Not Found'); err.status = 404; next(err); }); // The user logs module app.use(userLogs); // Configure error reporting if (process.env.RAVEN_DSN) { app.use(Raven.errorHandler()); } // Error handler app.use((err, req, res) => { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.send({ error: 'Something failed!' }); }); // Setup the ip and port app.set('port', process.env.APP_PORT || 8000); app.set('ip', process.env.APP_IP || '127.0.0.1'); // Start the app app.listen(app.get('port'), () => { /* eslint-disable no-console */ console.log('***************************************************************'); console.log(`Server started on ${Date(Date.now())}`); console.log(`Server is listening on port ${app.get('port')}`); console.log('***************************************************************'); }); module.exports = app; 。如果我删除它并尝试仅设置状态,则api得到卡住(从前面说明挂起并且api什么都不做)。知道怎么做吗?

我的app.js:

app.use(userLogs);

const router = express.Router(); const routeHandler = ({ path, callback, method }) => { router.route(path)[method](async (req, res, next) => { try { await callback(req, res, next); } catch (error) { next(error); } }); }; routeHandler({ path: '/companies', callback: createCompany, method: 'post' }); routeHandler({ path: '/companies', callback: updateCompany, method: 'put' }); 是我附加日志的地方。

我的路线文件如下所示:

export const updateCompany = async (req, res) => {
  const companyData = req.body;

  // Get the data and update the company

  res.send({ message: 'Success!' });
};

让我们来看看updateCompany函数:

const userLogs = async (req, res, next) => {
  console.log(req);
  console.log('--------------------------------------------------------------------------');

};

UserLogs中间件:

@import url('webfonts/font-awesome-pro-5.0.1.css');
@import url('webfonts/fa-solid-900.ttf');
@import url('webfonts/fa-solid-900.woff');
@import url('webfonts/fa-solid-900.woff2');
@import url('webfonts/fa-regular-400.ttf');
@import url('webfonts/fa-regular-400.woff');
@import url('webfonts/fa-regular-400.woff2');

0 个答案:

没有答案