如何dynamic路由页面?
我如何dynamic路由每个页面而不使用app.get()每次? 我的代码也返回了404错误代码
console.log(page + " rendered");
不会因为某种原因而工作。
var express = require('express'); var path = require('path'); var ejs = require('ejs'); var app = express(); app.engine('.html', ejs.__express); app.set('views', __dirname + '/views'); app.set('view engine', 'html'); var pages = [ 'users', 'index' ]; pages.forEach(function(page) { app.get('/' + page, function(request, response) { response.render(page); console.log(page + " rendered"); }); console.log(page + " set up"); }); app.listen(80); console.log('Express app started on port %d', 80);
在你的路线中使用正则expression式。 ^和$分别表示开始和结束的分别。 | 表示或。 正则expression式是你的需求是/^(users|index)$/
。
app.get(/^(users|index)$/, function (req, res, next) { response.render(req.params[0]); console.log(req.params[0] + " rendered"); });
而不是为每个页面创build一个新的路线,你可能想dynamic地查找url的视图。 如果不处理处理程序中的path,请确保调用next()
以便调用其他路由和/或中间件。
var routes = { '/users': 'users rendered', '/index': 'index rendered', } app.get('*', (req, res, next) => { let view = routes[req.path] if (!view) return next() res.render(view) }) app.use((req, res, next) => { res.status(404).send('404 - Not found') })
这是我使用express的dynamic路由架构,您可能可以重新使用它来满足您的需求。 它需要把一些“元数据”放入一个对象(路由)数组中,
"use strict"; let express = require("express"); let routing = (req, res) => { let router = express.Router(), // "meta-data" for routes routes = [{ path: "/", view: "default", title: "root" }, { path: "/otherpath", view: "otherfile", title: "otherpage" }]; // iterates through routes looking for req.path let routeIndex = routes.findIndex(route => route.path === req.path); // if object in routes found with matching path if (routeIndex >= 0) { // serves content res.status(200).render(routes[routeIndex].view, { title: routes[routeIndex].title }); } else { // else 404s console.log("404 from request: ", req.path); res.status(404).sendFile(process.cwd() + "/views/404filename.htm"); } return router }; module.exports = routing;
app.use('/', function(req, res) { // whatever });
这将匹配一切。 在callback里面,你可以做渲染(你可以通过req
对象访问请求来渲染合适的页面)。 请参阅app.use 。
- NodeJS请求:如何获得响应作为一个string?
- EJS错误:未定义; 找不到模块'undefined'; 找不到模块'ejs'; 身体没有定义
- Node.js和AngularJS中的CORS
- button单击Jade没有脚本标记
- 你如何dynamic地设置一个Jade模板的布局,以在Node.js / Express 3.0中进行扩展?
- NodeJs,ExpressJs,Mongoose中的MVC客户端validation
- 表示3.0 bodyParser无法正常工作
- configurationNode.js / Express服务器以使用React-Router BrowserRouter
- Express路由器未安装