我不知道这样做的函数,有人知道吗?
当前回答
上面的答案很好,但其中一半的答案不会返回404作为HTTP状态代码,而另一半答案则不能呈现自定义模板。在Expressjs中拥有自定义错误页面(404)的最佳方法是
app.use(function(req, res, next){
res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});
将此代码放在所有URL映射的末尾。
其他回答
你问题的答案是:
app.use(function(req, res) {
res.status(404).end('error');
});
有一篇很棒的文章讲述了为什么这是最好的方法。
我认为你应该首先定义你所有的路线,然后作为最后的路线添加
//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?
如果您使用express-generator包:
下(err);
这段代码将您发送到404中间件。
app.get('*',function(req,res){
res.redirect('/login');
});
覆盖express中的所有HTTP动词
为了覆盖所有HTTP动词和所有剩余路径,您可以使用:
app.all('*', cb)
最终的解决方案是这样的:
app.all('*', (req, res) =>{
res.status(404).json({
success: false,
data: '404'
})
})
你不应该忘记把路由器放在最后。 因为路由器的顺序很重要。
推荐文章
- 有没有办法修复包锁。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