当用户在我的网站上输入错误的网址时,如何将他们重定向到错误页面?仍处于设计模式

问题描述 投票:0回答:1

我正在构建一个电子商务进行测试,我希望不在我的数据库中的任何页面直接进入我的错误页面,以便用户仍然可以留在网站上并希望参与网站上的其他活动。 我正在使用普通的 javascript。

`

const express = require('express');
const app = express();
app.post('/submit-form', (req, res) => {
    if (!isValid(req.body)) {
        res.redirect('/error');
    } else {
        res.send('Form submitted successfully!');
    }
});
app.get('/error', (req, res) => {
    res.sendFile(__dirname + '/public/error.html');`your text`
});
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

` 这是我后端的错误文件,我该如何修改它才能得到我想要的结果?

javascript error-handling http-status-code-404 custom-error-pages
1个回答
0
投票

您绝对可以使用通配符路由(*)方法和中间件来处理用户尝试访问数据库中不存在的页面的情况。这是使用通配符路由修改后的中间件:

app.use((req, res, next) => {
// Assuming you have a function to check if the requested page exists in your database
if (!isPageInDatabase(req.url)) {
    res.redirect('/error');
} else {
    next(); 
}

});

该中间件将拦截所有请求并检查所请求的页面是否存在于您的数据库中。如果没有,它会将用户重定向到错误页面。

关于表单提交案例,如果您的表单操作正确设置为 /submit-form 并且表单提交期间出现错误,则现有代码应该按预期工作,将用户重定向到错误页面。请交叉检查表单操作是否不同,在这种情况下,您可能需要相应地调整路线。

© www.soinside.com 2019 - 2024. All rights reserved.