1

var express = require('express');
var path = require('path');

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

I confused when catch 404 error and when not? I want achieve the goal when input correct request path will not catch 404 error,otherwise bad request path will.

ivanJF
  • 13
  • 1
  • 4
  • [Related post for catching 404s](http://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs) – user82395214 Mar 05 '17 at 03:33

2 Answers2

2

In your routes folder(if you are using express-gen) or anywhere else create a node module which uses express.router() as follows

var express = require('express');
var bodyParser = require('body-parser');

var dishRouter = express.Router();

dishRouter.use(bodyParser.json());

Then handle your requests, example:

dishRouter.route('/')
.get(function(req, res, next) {
    res.end('Will send all the dishes to you!');
})

.post(function(req, res, next) {
    res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description);
});

And use this in ur app.js or the main file which you run:

var express = require('express');
var path = require('path');
var dishRouter=require('./routes/dishRouter');

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

app.use('/dishes',dishRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  res.redirect('/fail');
  next(err);
});

So what this will do is that, it will handle the get and post requests from client for URI /dishes and for others, it will throw an error 404 and send to /fail path.

Ashniu123
  • 347
  • 4
  • 13
1

Remember the express use() is executed for all request, so what is happening is your 404 status is attached to all request within your application. Use it in the callback which checks whether the input is correct or not, for example if its an HTTP express post request:

// This is just an example, please note
app.post('/signin', function(req, res) {
    if(!user.passwordCheck(req.body.password) {
        res.status(404).send({
            message: 'Incorrect input'
        }); 
    } else res.redirect('/success');
}

I hope this helps.