首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用express来制作Nodejs中的中间件

如何使用express来制作Nodejs中的中间件
EN

Stack Overflow用户
提问于 2019-03-26 00:54:07
回答 1查看 0关注 0票数 0

我正在制作极速路由器。 有一些代码如下。 但是当我运行node这个文件时,它不起作用。 我认为这部分会产生一些问题。 这适用于Koa但不表达。 你能给我一些建议吗?

const printInfo = (req) => {
  req.body = {
    method: req.method,
    path: req.path,
    params: req.params,
  };
};

这是连续的代码。

const express = require('express');
const posts = express.Router();

const printInfo = (req) => {
  req.body = {
    method: req.method,
    path: req.path,
    params: req.params,
  };
};

posts.get('/', printInfo);

module.exports = posts;

const express = require('express');

const api = express.Router();
const posts = require('./posts');

api.use('/posts', posts);

module.exports = api;

const express = require('express');

const app = express();
const api = require('./api/index');

app.use('/api', api);

app.listen(4000, () => {
  console.log('Example app listening on port 4000!');
});
EN

回答 1

Stack Overflow用户

发布于 2019-03-26 10:48:29

您的中间件错过了next()调用,并且路由器配置不正确。

按照这个例子,我总是使用Expressjs中间件

middleware.js

// no need to import express/router

module.exports = (req, res, next) => {

  // manipulate your body obj
  req.body = {
    method: req.method,
    path: req.path,
    params: req.params,
  };

  // go to the next function
  next();

}

routes.js

// only import the router
const router = require('express').Router();

// function for /api/posts
router.route('/posts').post( (req, res) => {
    // req.body has been manipulated from the middleware
    // do anything you like and call res
    res.send("...")
});

// other routes

module.exports = router;

server.js

const express = require('express');
const middleware = require('./middleware');
const routes = require('./routes');

const app = express();

// all calls to /api/* execute the middleware first
app.use('/api', middleware);

// execute the other routes functions
app.use('/api', routes);

app.listen(4000, () => {
  console.log('Example app listening on port 4000!');
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档