【问题标题】:Routes priority in express快递路线优先
【发布时间】:2016-07-03 12:51:33
【问题描述】:

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

目前我是这样做的:

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 自定义错误页面?

【问题讨论】:

  • 我认为是res.send
  • @JasterTDCClan 是的,可能是错字。 :) 不确定,但也许end 也可以。
  • 我的静态文件代码中有这个app.use(express.static(__dirname + '/public'));
  • 当您在 javascript 代码中请求类似 require('/js/jquery.min.js') 的内容时,express 会查看您的静态目录。

标签: javascript node.js http express


【解决方案1】:

考虑到您的静态文件位于相对于您的index.jspublic 文件夹中,这可以按预期工作:

文件夹结构:

- 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的输出:

$ http get 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.

【讨论】:

  • 谢谢!嗯,有趣。在这里和我设置的一个最小示例中工作,但现在在我的应用程序中......调试。
  • 啊,不是app.use,而是myRouter.use(/* handle errors */)。也许你对this question too有一个很好的答案。
  • 刚刚做了。非常感谢!
  • 更新了我的答案。把app.use(router)放到最后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
相关资源
最近更新 更多