我不知道这样做的功能,有人知道吗?
答案 0 :(得分:255)
我发现这个例子非常有帮助:
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');
});
答案 1 :(得分:139)
我认为您应首先定义所有路线,并作为最后一条路线添加
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).send('what???');
});
一个可行的示例应用:
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?
答案 2 :(得分:31)
您可以将中间件放在引发NotFound
错误的最后位置,
甚至直接渲染404页面:
app.use(function(req,res){
res.status(404).render('404.jade');
});
答案 3 :(得分:31)
以上答案都很好,但在其中一半中,您将无法获得404作为您的HTTP状态代码返回,而在另一半中,您将无法进行自定义模板渲染。在Expressjs中拥有自定义错误页面(404)的最佳方法是
app.use(function(req, res, next){
res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});
将此代码放在所有网址映射的末尾。
答案 4 :(得分:4)
在app.js的最后一行只是放了这个功能。这将覆盖默认的page-not-found错误页面:
app.use(function (req, res) {
res.status(404).render('error');
});
它将覆盖所有没有有效处理程序的请求并呈现您自己的错误页面。
答案 5 :(得分:4)
答案 6 :(得分:3)
https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js
这就是node-boilerplate的作用。
答案 7 :(得分:3)
在某些情况下,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");
});
答案 8 :(得分:3)
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'
}
});
答案 9 :(得分:2)
// 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');
});
答案 10 :(得分:1)
虽然上面的答案是正确的,但对于那些想要在IISNODE中工作的人,您还需要指定
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
<configuration>
你的web.config中的(否则IIS会占用你的输出)。
答案 11 :(得分:1)
您可以根据内容类型进行错误处理
此外,根据状态代码进行处理。
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.jade
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.accepts()
。
如果前一代码中出现500错误,则调用if(500 == err.status){. . . }
答案 12 :(得分:1)
最简单的方法是完全捕获错误页面
// 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}`);
})
现在这应该显示所有无法识别的端点的错误页面!
答案 13 :(得分:1)
嗨,请找到答案
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello home!'));
app.get('/about-us', (req, res) => res.send('Hello about us!'));
app.post('/user/set-profile', (req, res) => res.send('Hello profile!'));
//last 404 page
app.get('*', (req, res) => res.send('Page Not found 404'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
答案 14 :(得分:0)
在 Express 中,404 响应不是错误的结果,因此错误处理程序中间件不会捕获它们。您需要做的就是在堆栈的最底部(在所有其他函数下方)添加一个中间件函数来处理 404 响应:
app.use(function (req, res, next) {
// YOU CAN CREATE A CUSTOM EJS FILE TO SHOW CUSTOM ERROR MESSAGE
res.status(404).render("404.ejs")
})
答案 15 :(得分:0)
定义所有路由后我要做的是捕获潜在的 404 并转发到错误处理程序,如下所示:
@Echo off
:Menu
Echo [E]xit [L]ogoff [R]estart [S]hutdown
For /F "Delims=" %%G in ('Choice /N /C:SRLE')Do (
If %%G==S Call :Timer "Shutdown /SG /T 1" "Shutting Down"
If %%G==R Call :Timer "Shutdown /R /T 1" "Restarting"
If %%G==L Call :Timer "Shutdown /L" "Logging Off"
If %%G==E Exit /B
)
:# On Cancel Command Selection:
Goto :Menu
:# Function With timer
:Timer [Command] [Prompt]
For /L %%i in (30 -1 1)Do (
Cls
Echo %~2 in : %%i Seconds [C]ancel [R]estart Timer [N]o wait
For /F "Delims=" %%G in ('Choice /T 1 /N /C:CRNW /D W')Do (
If %%G==R Goto :Timer
If %%G==C Goto :Eof
If %%G==N %~1
)
)
%~1
答案 16 :(得分:0)
上面的代码对我不起作用。
所以我找到了一个切实可行的新解决方案!
app.use(function(req, res, next) {
res.status(404).send('Unable to find the requested resource!');
});
或者您甚至可以将其渲染到404页面。
app.use(function(req, res, next) {
res.status(404).render("404page");
});
希望这对您有所帮助!
答案 17 :(得分:0)
express
中的所有HTTP动词为了覆盖all HTTP verbs和所有剩余路径,您可以使用:
app.all('*', cb)
最终解决方案如下:
app.all('*', (req, res) =>{
res.status(404).json({
success: false,
data: '404'
})
})
您不应忘记将路由器放在最后。 因为路由器的顺序很重要。
答案 18 :(得分:0)
应该在对app.listen.Express的调用在路由路径中支持*之前设置404页面。这是一个匹配的特殊字符 任何东西。可以用来创建匹配所有请求的路由处理程序。
app.get('*', (req, res) => {
res.render('404', {
title: '404',
name: 'test',
errorMessage: 'Page not found.'
})
})````
答案 19 :(得分:0)
如果要从功能(路线)重定向到错误页面,请执行以下操作-
在您的app.js中添加常规错误消息代码-
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
// you can also serve different error pages
// for example sake, I am just responding with simple error messages
res.status(err.status || 500)
if(err.status === 403){
return res.send('Action forbidden!');
}
if(err.status === 404){
return res.send('Page not found!');
}
// when status is 500, error handler
if(err.status === 500) {
return res.send('Server error occured!');
}
res.render('error')
})
在您的函数中,可以使用设置错误状态,然后使用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()
}
答案 20 :(得分:0)
我使用下面的处理程序处理带有静态.ejs
文件的404错误。
将此代码放入路线脚本中,然后在file.js
/ app.use()
/ app.js
中要求server.js
到www.js
(如果使用) IntelliJ for NodeJS)
您还可以使用静态.html
文件。
//Unknown route handler
router.get("[otherRoute]", function(request, response) {
response.status(404);
response.render("error404.[ejs]/[html]");
response.end();
});
这样,正在运行的快速服务器将使用正确的404 error
进行响应,并且您的网站还可以包含正确显示服务器404响应的页面。您还可以在navbar
中添加404 error template
,其中包含指向您网站其他重要内容的内容。
答案 21 :(得分:0)
要发送到自定义页面:
app.get('*', function(req, res){
if (req.accepts('html')) {
res.send('404', '<script>location.href = "/the-404-page.html";</script>');
return;
}
});
答案 22 :(得分:0)
如果您使用快速生成器包:
下(ERR);
此代码将您发送到404中间件。