简体   繁体   中英

Redirect to a new page in node js express?

I am creating a chat app in node js using socket.io. When a new user logs in to localhost:3000, a form is given in which you enter your name and room you want to enter. How can i redirect this user to the appropriate room, as soon as submit button is pressed ? My server by dafault displays login.html when localhost:3000 is connected to, and i want that on clicking submit, a new request is made such that the second app.get can serve it.

app.get("/", function(req, res) {
    res.sendFile(__dirname + "/login.html");
});
app.get("/room", function(req,res) {
    res.sendFile(__dirname + "/chat.html");
});

The form in login.html -

var myForm2 = document.getElementById("myForm2");
myForm2.addEventListener("submit", function(e) {
    e.preventDefault();
    document.location = "localhost:3000/room";
});

You can use res.redirect([status,] path) like this:

if (input_are_ok) {
    res.redirect('public/index.html');
}

This will redirect to the given URL using the specified HTTP status code status. If no status code is specified, the status code defaults to 302 (which is fine in most use cases)

When the form is submit, the browser turns that form into a HTTP request, using the inputs as parameters for query string. let's say you have a form like this in login.html:

<form action="/chat.html">
    <label>Display username</label>
    <input type="text" name="username" placeholder="Display name" required>
    <label>Room</label>
    <input type="text" name="room" placeholder="Room" required>
    <button>Join</button>
</form>

Once you clicked it this html page will be redirected to /chat route with 2 string parameters. your url will be like this:

http://localhost:3000/chat.html?username=yourUserName&room=yourRoom

Now you need to create a chat.html and this page will be displayed upon submit.

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