How can redirect my user to error page whenever they input a wrong url on my site? its still in design mode

31 Views Asked by At

I'm building an ecommerce site for testing. I want any page not in my database go straight to my error page so users can still stay on the site and want to engage in other activities on the site.

This is my error file in my backend. How can I modify it to get my desired result? I'm using vanilla 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');
});
1

There are 1 best solutions below

0
Ritik Goyal On

You can definitely use the wildcard route (*) approach along with middleware to handle cases where users try to access pages not present in your database. Here's the modified middleware using the wildcard route:

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

});

This middleware will intercept all requests and check if the requested page exists in your database. If not, it will redirect the user to the error page.

Regarding the form submission case,if your form action is set correctly to /submit-form and there's an error during form submission, the existing code should work as expected to redirect the user to the error page. Please cross check if the form action differs, in such cases, you might need to adjust the route accordingly.