路由优先快递

时间:2016-03-17 09:13:42

标签: javascript node.js http express

我想在express中实现以下路由的优先级(按此顺序):自定义网址,静态文件,错误页面。

目前我这样做了:

let router = express.Router();

// custom urls (defined by me)
router.get("/foo", ...);

app.use(router);

// static files
app.use("/", express.static("path/to/public"));

// error pages (404, 500):
router.use((req, res, next) => { res.send("Custom 404 page."); });
router.use((err, req, res, next) => { res.send("Custom 500 page."); });

我遇到的问题是我得到Custom 404 page静态文件。如果我删除错误页面路由,静态文件工作正常,但我没有自定义404错误页面和500错误页面。

如何在保持此优先权的同时处理400500自定义错误页面?

1 个答案:

答案 0 :(得分:3)

考虑到您的静态文件位于相对于public的{​​{1}}文件夹中,这可以按预期工作:

文件夹结构:

index.js

您的- index.js - public - index.html

index.js

"use strict"; let express = require('express'); let app = express(); let router = express.Router(); // custom urls (defined by me) app.get("/foo", function(req,res) { res.send('yay') }); // static files app.use("/", express.static("public")); // error pages (404, 500): router.use((req, res, next) => { res.send("Custom 404 page."); }); router.use((err, req, res, next) => { res.send("Custom 500 page."); }); app.use(router); // put it here instead of the beginning app.listen(6666); 的输出:

/foo

$ http get localhost:6666/foo HTTP/1.1 200 OK Connection: keep-alive Content-Length: 3 Content-Type: text/html; charset=utf-8 Date: Thu, 17 Mar 2016 09:54:30 GMT ETag: W/"3-QCrLHD4/N9puG7bKytwxXQ" X-Powered-By: Express yay 的输出:

/

$ http get localhost:6666 HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: public, max-age=0 Connection: keep-alive Content-Length: 129 Content-Type: text/html; charset=UTF-8 Date: Thu, 17 Mar 2016 09:51:15 GMT ETag: W/"81-15383fa840c" Last-Modified: Thu, 17 Mar 2016 09:49:06 GMT X-Powered-By: Express <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Yay!!! </body> </html> 的输出:

/bar