Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

node.js - Error #404 Page Not Working with Express

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...