I don't know a function for doing this, does anyone know of one?
I don't know a function for doing this, does anyone know of one?
I found this example quite helpful:
https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js
So, it is actually this part:
// "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');
});
The easiest way to do it is to have a catch all for Error Page
// Step 1: calling express
const express = require("express");
const app = express();
Then
// require Path to get file locations
const path = require("path");
Now you can store all your "html" pages (including an error "html" page) in a variable
// 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
Now you simply call the pages using the Get Method and have a catch all for any routes not available to direct to your error page using 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);
});
Don't forget to set up a Port and Listen for server:
// Setting port to listen on
const port = process.env.PORT || 8000;
// Listening on port
app.listen(port, function(){
console.log(`http://localhost:${port}`);
})
This should now show your error page for all unrecognized endpoints!
Hi please find the answer
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}!`));
expressIn order to cover all HTTP verbs and all remaining paths you could use:
app.all('*', cb)
Final solution would look like so:
app.all('*', (req, res) =>{
res.status(404).json({
success: false,
data: '404'
})
})
You shouldn't forget to put the router in the end. Because order of routers matter.
The above code didn't work for me.
So I found a new solution that actually works!
app.use(function(req, res, next) {
res.status(404).send('Unable to find the requested resource!');
});
Or you can even render it to a 404 page.
app.use(function(req, res, next) {
res.status(404).render("404page");
});
Hope this helped you!
you can error handling according to content-type
Additionally, handling according to status code.
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
If you can using res.format, You can write simple error handling code.
Recommendation res.format() instead of res.accepts().
If the 500 error occurs in the previous code, if(500 == err.status){. . . } is called
In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:
app.use(function (req, res, next) {
// YOU CAN CREATE A CUSTOM EJS FILE TO SHOW CUSTOM ERROR MESSAGE
res.status(404).render("404.ejs")
})
If you want to redirect to error pages from your functions (routes) then do following things -
Add general error messages code in your 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')
})
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()
}
The 404 page should be set up just before the call to app.listen.Express has support for * in route paths. This is a special character which matches anything. This can be used to create a route handler that matches all requests.
app.get('*', (req, res) => {
res.render('404', {
title: '404',
name: 'test',
errorMessage: 'Page not found.'
})
})
What I do after defining all routes is to catch potential 404 and forward to error handler, like this:
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;
First, create a route js file. Next, create a error.ejs file (if you are using ejs). Finally, add the following code in your route file
router.get('*', function(req, res){
res.render('error');
});
This method is easier, but it has to be the last thing after all your routes.
app.use( (req, res) => {
//render page not found
res.render('404')
})