我刚刚开始使用Nodejs Express路由器
app.use('/', (req, res, next) => {
res.sendFile(path.join(__dirname, "views", "welcome.html"));
});
这会将我转至http://localho.st:3000 /进入欢迎页面
我想将其余的不可用页面重定向到未找到的页面,我尝试执行以下操作,我知道上面和下面的代码基于将执行的先到先得原则相同。
但是我想知道我还能如何处理(将'/'以外的所有其他页面路由到404)?
app.use((req, res, next) => {
res.send('<h1>Page Not Found ! </h1>');
});
我也尝试过-参考:评论#1
app.use('/', (req, res) => {
res.sendFile(path.join(__dirname, "views", "welcome.html"));
});
app.get('*',(req, res) => {
res.send('<h1>Page Not Found ! </h1>');
});
答案。 :changed app.use('/',...) to app.get('/',...) worked for me
💡出现错误的唯一原因是因为您要添加中间件:
Not found
位于所有路径的上方。这就是为什么您会遇到一些错误。
👨🏫确保您的代码看起来像below以下的代码:
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "views", "welcome.html"));
});
app.get("*", (req, res) => {
res.send("<h1>Page Not Found ! </h1>");
});
app.listen(8080, () => {
console.log("Server is up");
});
💡之后,您可以在同一目录中创建
views
文件夹并将welcome.html
放在其中。
[作为示例,您可以在我的代码中看到沙箱:https://codesandbox.io/s/eloquent-elion-p1hcj
希望它能对您有所帮助。