我在做快递路由器。
有一些类似下面的代码。
但是当我运行该文件时,它不起作用。
我认为这部分问题。
这在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!');
});
答案 0 :(得分:0)
您的中间件错过了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!');
});