gpt4 book ai didi

javascript - express 中的路线优先级

转载 作者:可可西里 更新时间:2023-11-01 17:00:58 25 4
gpt4 key购买 nike

我想在 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 错误页面。

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

最佳答案

考虑到您的静态文件位于与您的 index.js 相关的 public 文件夹中,这按预期工作:

文件夹结构:

- 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.

关于javascript - express 中的路线优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36056056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com