Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I test my Error #404 page, I get the default "Not Found."

require('html');
var WebSocketServer = require('ws').Server
    , http = require('http')
    , fs = require('fs')
    , express = require('express')
    , app = express();

app.use(express.static(__dirname + '/public'));

var server = http.createServer(app);
server.listen(42069);

var MainServer = new WebSocketServer({server: server});

// Handle 404
app.use(function(req, res) {
    res.status(404).render('/error/404.html',{title: "Error #404"});
});

However, it does work with

app.use(function(req, res) {
    res.status(404).render('/error/404.html',{title: "Error #404"});
});

but I don't want to be redirected to my 404 page, I want it to be rendered on any non-existent address.

Any thoughts on how to get this to work?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could try something like this after your route handling

app.get('/404', function(req, res, next){
  // trigger a 404 since no other middleware
  // will match /404 after this one, and we're not
  // responding here
  next();
});


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...