Making a function an express middleware in a route
所以我有一条路线,并且路线中有一些丑陋的代码,我想制作一个中间件。唯一的问题是 Express 的文档不清楚,我的代码只有 404s。
我怎样才能做到这一点?
路线:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | router.get('/product/:slug', function(req, res) { //route params var slug = req.params.slug; var productResp; //scope up api response to pass to render() console.log(slug); //api call Prismic.api("https://prismic.io/api").then(function(api) { return api.getByUID('product' , slug); }).then(function(response) { app.use(markedHtml) }) .catch(function(error) { res.render('404'); }) }); |
功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | var markedHtml = function(req, res, next) { var md_col_1 = response.data["product.markdown-col-one"].value[0].text; var md_col_1_1 = response.data["product.markdown-col-one"].value[1].text; var md_col_2 = response.data["product.markdown-col-two"].value[0].text; var md_col_2_1 = response.data["product.markdown-col-two"].value[1].text; var md_col_3 = response.data["product.markdown-col-three"].value[0].text; var md_col_3_1 = response.data["product.markdown-col-three"].value[1].text; var html_col_1 = marked(md_col_1); var html_col_1_1 = marked(md_col_1_1); var html_col_2 = marked(md_col_2); var html_col_2_1 = marked(md_col_2_1); var html_col_3 = marked(md_col_3); var html_col_3_1 = marked(md_col_3_1); res.render('product-template', { product: response, md_one: html_col_1, md_one_1: html_col_1_1, md_two: html_col_2, md_two_1: html_col_2_1, md_three: html_col_3, md_three_1: html_col_3_1, }) next(); } |
在您的根目录
在
1 2 | const markedHtml = require('./middleware/markedHtml'); app.use('/product/:slug', markedHtml); |
在
1 2 3 4 5 6 7 8 9 10 | const markedHtml = function(req, res, next) { // Do stuff with req.apiResponse here. ... res.render('product-template', { ... }); } module.exports = markedHtml; |
您的原始路线将如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | router.get('/product/:slug', function(req, res, next) { //route params var slug = req.params.slug; var productResp; //scope up api response to pass to render() console.log(slug); //api call Prismic.api("https://prismic.io/api").then(function(api) { return api.getByUID('product' , slug); }).then(function(response) { req.apiResponse = response; next(); }) .catch(function(error) { res.render('404'); }); }); |
基本上,您的原始路由将接收客户端请求,执行 API 调用等,然后(双关语!)运行到
如果有任何不清楚或需要额外解释,请告诉我。
可以在此处找到其他文档:http://expressjs.com/en/4x/api.html#app.use