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


当前回答

覆盖express中的所有HTTP动词

为了覆盖所有HTTP动词和所有剩余路径,您可以使用:

app.all('*', cb)

最终的解决方案是这样的:

app.all('*', (req, res) =>{
    res.status(404).json({
        success: false,
        data: '404'
    })
})

你不应该忘记把路由器放在最后。 因为路由器的顺序很重要。

其他回答

我认为你应该首先定义你所有的路线,然后作为最后的路线添加

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.status(404).send('what???');
});

一个示例应用程序的工作:

app.js:

var express = require('express'),
    app = express.createServer();

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

app.get('/', function(req, res){
  res.send('hello world');
});

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000, '127.0.0.1');

alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt 

.
./app.js
./public
./public/README.txt

alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?

做到这一点最简单的方法是为错误页提供一个捕捉

// Step 1: calling express
const express = require("express");
const app = express();

Then

// require Path to get file locations
const path = require("path");

现在您可以将所有的“html”页面(包括错误的“html”页面)存储在一个变量中

// Storing file locations in a variable
var indexPg = path.join(__dirname, "./htmlPages/index.html");
var aboutPg = path.join(__dirname, "./htmlPages/about.html");
var contactPg = path.join(__dirname, "./htmlPages/contact.html");
var errorPg = path.join(__dirname, "./htmlPages/404.html"); //this is your error page

现在你只需使用Get方法调用页面,并使用app.get("*")捕获所有不可用的路由,以指向你的错误页面。

//Step 2: Defining Routes
//default page will be your index.html
app.get("/", function(req,res){
  res.sendFile(indexPg);
});
//about page
app.get("/about", function(req,res){
  res.sendFile(aboutPg);
});
//contact page
app.get("/contact", function(req,res){
  res.sendFile(contactPg);
});
//catch all endpoint will be Error Page
app.get("*", function(req,res){
  res.sendFile(errorPg);
});

不要忘记设置一个端口和监听服务器:

// Setting port to listen on
const port = process.env.PORT || 8000;
// Listening on port
app.listen(port, function(){
  console.log(`http://localhost:${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){…}被调用

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

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() }

嗨,请找到答案

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