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


当前回答

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

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

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){…}被调用

其他回答

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

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

我发现这个例子很有帮助:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

所以,它实际上是这一部分:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

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.json({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

首先,创建一个route js文件。接下来,创建一个错误。Ejs文件(如果您正在使用Ejs)。最后,在路由文件中添加以下代码

router.get('*', function(req, res){
    res.render('error');
});

404页面应该在调用app.listen.Express支持路由路径中的*之前设置。这是一个匹配的特殊字符 任何东西。这可以用来创建一个匹配所有请求的路由处理程序。

app.get('*', (req, res) => {
  res.render('404', {
    title: '404',
    name: 'test',
    errorMessage: 'Page not found.'
  })
})

如果你想从你的函数(路由)重定向到错误页面,那么做以下事情-

Add general error messages code in your app.js - 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 // you can also serve different error pages // for example sake, I am just responding with simple error messages res.status(err.status || 500) if(err.status === 403){ return res.send('Action forbidden!'); } if(err.status === 404){ return res.send('Page not found!'); } // when status is 500, error handler if(err.status === 500) { return res.send('Server error occured!'); } res.render('error') }) In your function, instead of using a error-page redirect you can use set the error status first and then use next() for the code flow to go through above code - if(FOUND){ ... }else{ // redirecting to general error page // any error code can be used (provided you have handled its error response) res.status(404) // calling next() will make the control to go call the step 1. error code // it will return the error response according to the error code given (provided you have handled its error response) next() }