//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?
// "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.json({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
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...
}
}
});
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");
});
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
// 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
//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}`);
})
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')
})
In your function, instead of using a error-page redirect you can use set the error status first and then use next() for the code flow to go through above code -
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()
}