错误#404页面不适用于Express [英] Error #404 Page Not Working with Express

查看:57
本文介绍了错误#404页面不适用于Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我测试我的错误#404页面时,会得到默认的未找到".

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

但是,它确实可以工作

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

但是我不想重定向到我的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?

谢谢!

推荐答案

您可以尝试类似

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

这篇关于错误#404页面不适用于Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆