我不知道这样做的函数,有人知道吗?
当前回答
发送到自定义页面:
app.get('*', function(req, res){
if (req.accepts('html')) {
res.send('404', '<script>location.href = "/the-404-page.html";</script>');
return;
}
});
其他回答
// Add this middleware
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.get('*',function(req,res){
res.redirect('/login');
});
虽然上面的答案是正确的,但对于那些希望在IISNODE中工作的人来说,还需要指定
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
<configuration>
在你的网里。配置(否则IIS将吃掉您的输出)。
我在定义所有路由后所做的是捕捉潜在的404并转发到错误处理程序,如下所示:
const httpError = require('http-errors');
...
// API router
app.use('/api/', routes);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new httpError(404)
return next(err);
});
module.exports = app;
可以根据内容类型进行错误处理
此外,根据状态代码进行处理。
app.js
import express from 'express';
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// when status is 404, error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
if( 404 === err.status ){
res.format({
'text/plain': () => {
res.send({message: 'not found Data'});
},
'text/html': () => {
res.render('404.jade');
},
'application/json': () => {
res.send({message: 'not found Data'});
},
'default': () => {
res.status(406).send('Not Acceptable');
}
})
}
// when status is 500, error handler
if(500 === err.status) {
return res.send({message: 'error occur'});
}
});
404.玉
doctype html
html
head
title 404 Not Found
meta(http-equiv="Content-Type" content="text/html; charset=utf-8")
meta(name = "viewport" content="width=device-width, initial-scale=1.0 user-scalable=no")
body
h2 Not Found Page
h2 404 Error Code
如果可以使用res.format,可以编写简单的错误处理代码。
建议res.format()代替res. accepted()。
如果500错误发生在前面的代码中,如果(500 == err.status){…}被调用
推荐文章
- 有没有办法修复包锁。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