我不知道这样做的函数,有人知道吗?
当前回答
在app.js的最后一行放入这个函数。这将覆盖默认的page-not-found错误页面:
app.use(function (req, res) {
res.status(404).render('error');
});
它将覆盖没有有效处理程序的所有请求,并呈现您自己的错误页面。
其他回答
如果您使用express-generator包:
下(err);
这段代码将您发送到404中间件。
app.get('*',function(req,res){
res.redirect('/login');
});
Express-error-handler允许您为错误指定自定义模板、静态页面或错误处理程序。它还做了其他有用的错误处理,每个应用程序都应该实现,比如防止4xx错误DOS攻击,以及在不可恢复错误时优雅地关闭。以下是你如何做到你所要求的:
var errorHandler = require('express-error-handler'),
handler = errorHandler({
static: {
'404': 'path/to/static/404.html'
}
});
// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );
// Handle all unhandled errors:
app.use( handler );
或者对于自定义处理程序:
handler = errorHandler({
handlers: {
'404': function err404() {
// do some custom thing here...
}
}
});
或者对于自定义视图:
handler = errorHandler({
views: {
'404': '404.jade'
}
});
在某些情况下,404页面不能被写入并作为最后一个路由执行,特别是如果您有一个异步路由功能,从而引入了一个迟到的/路由。在这些情况下可以采用下面的模式。
var express = require("express.io"),
app = express(),
router = express.Router();
router.get("/hello", function (req, res) {
res.send("Hello World");
});
// Router is up here.
app.use(router);
app.use(function(req, res) {
res.send("Crime Scene 404. Do not repeat");
});
router.get("/late", function (req, res) {
res.send("Its OK to come late");
});
app.listen(8080, function (){
console.log("Ready");
});
我认为你应该首先定义你所有的路线,然后作为最后的路线添加
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).send('what???');
});
一个示例应用程序的工作:
app.js:
var express = require('express'),
app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send('hello world');
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000, '127.0.0.1');
alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt
.
./app.js
./public
./public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?
- 当WebSockets可用时,为什么要使用AJAX ?
- 使用过程。TypeScript中的env
- 如何找到哪些承诺未处理在Node.js UnhandledPromiseRejectionWarning?
- 如何卸载Yarn