我不知道这样做的函数,有人知道吗?


当前回答

你可以把一个中间件放在最后一个位置,它会抛出一个NotFound错误, 甚至直接渲染404页面:

app.use(function(req,res){
    res.status(404).render('404.jade');
});

其他回答

嗨,请找到答案

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}!`));

可以根据内容类型进行错误处理

此外,根据状态代码进行处理。

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.玉

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

如果可以使用res.format,可以编写简单的错误处理代码。

建议res.format()代替res. accepted()。

如果500错误发生在前面的代码中,如果(500 == err.status){…}被调用

https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js

这就是node-boilerplate所做的。

app.get('*',function(req,res){
 res.redirect('/login');
});

你问题的答案是:

app.use(function(req, res) {
    res.status(404).end('error');
});

有一篇很棒的文章讲述了为什么这是最好的方法。