Javascript 快车路线优先
我想在Javascript 快车路线优先,javascript,node.js,http,express,Javascript,Node.js,Http,Express,我想在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)
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."); });
我遇到的问题是,我得到了静态文件的自定义404页面
。如果我删除错误页面路由,静态文件可以正常工作,但我不会得到自定义的404错误页面和500错误页面
如何在保持此优先级的同时处理
400
和500
自定义错误页?考虑到您的静态文件位于相对于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>
我想是
res.send
@JasterTDCClan是的,可能是打字错误。)不确定,但可能end
也能工作。我在静态文件的代码app.use(express.static(\uu dirname+'/public'))中有这一点代码>。当您在javascript
代码中时,请求类似以下内容的require('/js/jquery.min.js')
express在您的静态目录中查找。谢谢!嗯,很有趣。在这里和我设置的一个最小示例中工作,但现在在我的应用程序中。。。调试.Ah,而不是app.use
我在做myRouter.use(/*handleerrors*/)
。也许你有一个很好的答案。谢谢!更新了我的答案。将app.use(路由器)
放在末尾。
$ 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.