简体   繁体   中英

Express.js - res.render and redirect at the same time

I am building a web app, including routes for authentication.

The Problem: When a registration succeeds I want to redirect to /login , but also include render options. But when I render the login.ejs the url stays /register .

The Options: I either have to find a way to use res.render and change the url OR use res.redirect and also pass render variables.

This is minimal code to show my problem:

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

app.post("/register", (res, req) => {
  // registration logic
  if(success) {
    res.render("login.ejs", {flag: "registration_success"})
  } 
}

the url shown is what you write in app.post("/someURL" not what you redirect to.

so if u want to redirect to login page after successful registration, simply redirect to "/login" . it renders "login.ejs"

about the part that you probably want to show a sign up success message, u can use 'flash' package; it helps you add data to memory and get it in client side and show a success message. I use sweetalert2 in such a way:

in back-end code:

req.flash('a-name-you-want', { flags, you, want });

to get these info in front-end:

<% let yourData = req.flash('the-name')
if(yourData.length) {
  // do sth to the data
}%>

I hope it helped you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM