javascript - Routes priority in express -
i want implement following routes' priority in express
(in order): custom urls, static files, error pages.
current did this:
let router = express.router(); // custom urls (defined 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."); });
the problem have i'm getting custom 404 page
static files. if remove error page routes, static files work fine, don't custom 404 error pages , 500 error pages.
how can handle 400
, 500
custom error pages while keeping priority too?
considering static files in public
folder relative index.js
, works expected:
folder structure:
- index.js - public - index.html
your index.js
:
"use strict"; let express = require('express'); let app = express(); let router = express.router(); // custom urls (defined 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 here instead of beginning app.listen(6666);
output of /foo
:
$ http 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
output of /
:
$ http 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>
output of /bar
:
$ http localhost:6666/bar http/1.1 200 ok connection: keep-alive content-length: 16 content-type: text/html; charset=utf-8 date: thu, 17 mar 2016 09:51:19 gmt etag: w/"10-creu2j3jd/vad5kvhqwlow" x-powered-by: express custom 404 page.
Comments
Post a Comment