node.jsexpresshttp-redirectbackendejs

How do I redirect a user from a certain page to another in Backend?


I am creating a Full-Stack website, but I have a slight problem when it comes to entering back to my index.ejs, as I want my Backend code to automatically redirect the user from "myPage/index.ejs" to just "myPage/". However, I really don't know how I'm going to go about doing this.

I am using JS with Express and Node.js for my backend, and EJS code for my frontend.

I currently have a basic setup like so:

//index.js

app.get("/", (req, res) => {
    res.render("index.ejs")
})

app.get("/index.ejs", (req, res) => {
    res.render("index.ejs")
})
<%# index.ejs (header.ejs) %>

<div class="Header">
    <h1 class="w">Vishesh's Site</h1>
    <a class="r" href="index.ejs">Home</a>
    <a class="r" href="about.ejs">About</a>
    <a class="r" href="contact.ejs">Contact</a>
</div>

However, when I am using this, the first loaded page has a nice URL of https://myPage/, but after clicking through my page and going to /about.ejs and what not, the link back to my homepage looks like so: https://myPage/index.ejs. This might create unnecessary confusion, so how do I revert back to the nice https://myPage/?

Unfortunately, all the redirects I found on the internet (And here!) had something to do with a JS command, location.href and location.replace. However, I am not sure how to implemement this code into my app.get() code.


Solution

  • I don't think you need to render index.ejs when the user goes to /index.ejs, i think you should just redirect any request to /index.ejs back to /

    it should look something like this:

    app.get("/", (req, res) => {
        res.render("index.ejs")
    })
    
    app.get("/index.ejs", (req, res) => {
       res.redirect("/")
    })
    

    the second code block just redirects back to /.

    also I think you need to add / to your navigation links to basically, they should look something like this:

    <a class="r" href="/">Home</a>
    <a class="r" href="/about.ejs">About</a>
    <a class="r" href="/contact.ejs">Contact</a>`
    

    hope this helps.