如何将404错误重定向到ExpressJS中的页面?

node.js Node.js

米亚

2020-03-23

我不知道执行此操作的功能,有人知道吗?

第2916篇《如何将404错误重定向到ExpressJS中的页面?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
阳光Tom 2020.03.23
宝儿 2020.03.23

最简单的方法是对错误页面进行全面捕获

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

然后

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

现在,这应该显示所有无法识别的端点的错误页面!

Tom伽罗 2020.03.23

在某些情况下,无法编写404页面作为最后一条路线执行,尤其是当您具有异步路由功能,该功能会在晚些时候将/ route引入聚会时。在这些情况下,可以采用以下模式。

var express = require("express.io"),
    app = express(),
    router = express.Router();

router.get("/hello", function (req, res) {
    res.send("Hello World");
});

// Router is up here.
app.use(router);

app.use(function(req, res) {
    res.send("Crime Scene 404. Do not repeat");
});

router.get("/late", function (req, res) {
    res.send("Its OK to come late");
});

app.listen(8080, function (){
    console.log("Ready");
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android