node跳转404.html,node.js - 如何将404错误重定向到ExpressJS中的页面?

node.js - 如何将404错误重定向到ExpressJS中的页面?

我不知道这样做的功能,有人知道吗?

18个解决方案

247 votes

我发现这个例子非常有帮助:

[https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js]

所以它实际上就是这个部分:

// "app.router" positions our routes

// above the middleware defined below,

// this means that Express will attempt

// to match & call routes _before_ continuing

// on, at which point we assume it's a 404 because

// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling

// middleware use()d, we assume 404, as nothing else

// responded.

// $ curl http://localhost:3000/notfound

// $ curl http://localhost:3000/notfound -H "Accept: application/json"

// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){

res.status(404);

// respond with html page

if (req.accepts('html')) {

res.render('404', { url: req.url });

return;

}

// respond with json

if (req.accepts('json')) {

res.send({ error: 'Not found' });

return;

}

// default to plain-text. send()

res.type('txt').send('Not found');

});

Felix answered 2019-04-06T17:28:53Z

124 votes

我认为您应首先定义所有路线,并作为最后一条路线添加

//The 404 Route (ALWAYS Keep this as the last route)

app.get('*', function(req, res){

res.send('what???', 404);

});

一个有效的示例应用程序:

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?

Alfred answered 2019-04-06T17:29:28Z

31 votes

您可以将中间件放在抛出NotFound错误的最后位置,

甚至直接渲染404页面:

app.use(function(req,res){

res.render('404.jade');

});

Ganesh Kumar answered 2019-04-06T17:29:59Z

30 votes

上面的答案是好的,但是其中一半你不会得到404作为你的HTTP状态代码返回,而在另一半,你将无法有自定义模板渲染。 在Expressjs中拥有自定义错误页面(404)的最佳方法是

app.use(function(req, res, next){

res.status(404).render('404_error_template', {title: "Sorry, page not found"});

});

将此代码放在所有URL映射的末尾。

Sushant Gupta answered 2019-04-06T17:30:30Z

4 votes

你的问题的答案是:

app.use(function(req, res) {

res.status(404).end('error');

});

有一篇很棒的文章说明为什么它是最好的方式。

Marius Cotofana answered 2019-04-06T17:31:01Z

4 votes

在app.js的最后一行只是放了这个函数。 这将覆盖默认的page-not-found错误页面:

app.use(function (req, res) {

res.render('error');

});

它将覆盖所有没有有效处理程序的请求并呈现您自己的错误页面。

Vivek Bajpai answered 2019-04-06T17:31:37Z

3 votes

[https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js]

这就是node-boilerplate的作用。

Lalith answered 2019-04-06T17:32:16Z

3 votes

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'

}

});

Eric Elliott answered 2019-04-06T17:32:55Z

3 votes

在某些情况下,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");

});

Dennis Mathew Philip answered 2019-04-06T17:33:19Z

2 votes

// 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');

});

ASHISH RANJAN answered 2019-04-06T17:33:36Z

1 votes

虽然上面的答案是正确的,但对于那些想要在IISNODE中工作的人,您还需要指定

在你的web.config中(否则IIS会占用你的输出)。

laktak answered 2019-04-06T17:34:07Z

1 votes

你可以根据内容类型进行错误处理

另外,根据状态代码进行处理。

if(500 == err.status){. . . }

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'});

}

});

if(500 == err.status){. . . }

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,则可以编写简单的错误处理代码。

建议if(500 == err.status){. . . }而不是res.accepts()。

如果先前代码中发生500错误,则调用if(500 == err.status){. . . }

멍개-mung answered 2019-04-06T17:35:35Z

0 votes

如果您使用快速生成器包:

下一个(ERR);

此代码将您发送到404中间件。

Josué Díaz answered 2019-04-06T17:36:13Z

0 votes

要发送到自定义页面:

app.get('*', function(req, res){

if (req.accepts('html')) {

res.send('404', '');

return;

}

});

Kristian answered 2019-04-06T17:36:38Z

0 votes

我使用下面的处理程序来处理404错误与静态404 error文件。

将此代码放在路由脚本中,然后在404 error template/server.js/www.js(如果使用IntelliJ for NodeJS)中要求404 error到navbar

您还可以使用静态404 error文件。

//Unknown route handler

router.get("[otherRoute]", function(request, response) {

response.status(404);

response.render("error404.[ejs]/[html]");

response.end();

});

这样,正在运行的快速服务器将使用适当的404 error进行响应,并且您的网站还可以包含正确显示服务器404响应的页面。 您还可以在404 error template中添加navbar,链接到您网站的其他重要内容。

mudrak patel answered 2019-04-06T17:37:38Z

0 votes

最简单的方法是对Error Page进行全部捕获

// Step 1: calling express

const express = require("express");

const app = express();

然后

// require Path to get file locations

const path = require("path");

现在,您可以将所有“html”页面(包括错误“html”页面)存储在变量中

// Storing file locations in a variable

var indexPg = path.join(__dirname, "./htmlPages/index.html");

var aboutPg = path.join(__dirname, "./htmlPages/about.html");

var contactPg = path.join(__dirname, "./htmlPages/contact.html");

var errorPg = path.join(__dirname, "./htmlPages/404.html"); //this is your error page

现在,您只需使用Get方法调用页面,并使用app.get(“*”)对所有无法指向错误页面的路径进行全部捕获

//Step 2: Defining Routes

//default page will be your index.html

app.get("/", function(req,res){

res.sendFile(indexPg);

});

//about page

app.get("/about", function(req,res){

res.sendFile(aboutPg);

});

//contact page

app.get("/contact", function(req,res){

res.sendFile(contactPg);

});

//catch all endpoint will be Error Page

app.get("*", function(req,res){

res.sendFile(errorPg);

});

不要忘记设置端口和侦听服务器:

// Setting port to listen on

const port = process.env.PORT || 8000;

// Listening on port

app.listen(port, function(){

console.log(`http://localhost:${port}`);

})

现在应该显示所有无法识别的端点的错误页面!

Kean Amaral answered 2019-04-06T17:38:39Z

0 votes

如果要从功能(路线)重定向到错误页面,请执行以下操作 -

在app.js中添加常规错误消息代码 -

if(FOUND){

...

}else{

// redirecting to general error page

// any error code can be used (provided you have handled its error response)

res.status(404)

// calling next() will make the control to go call the step 1. error code

// it will return the error response according to the error code given (provided you have handled its error response)

next()

}

在您的函数中,您可以先使用设置错误状态,然后使用next()代码流来查看错误页面重定向,而不是使用错误页面重定向 -

if(FOUND){

...

}else{

// redirecting to general error page

// any error code can be used (provided you have handled its error response)

res.status(404)

// calling next() will make the control to go call the step 1. error code

// it will return the error response according to the error code given (provided you have handled its error response)

next()

}

Anshul Bisht answered 2019-04-06T17:39:29Z

-2 votes

app.get('*',function(req,res){

res.redirect('/login');

});

s srinivas answered 2019-04-06T17:39:49Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值