Dhruv Chadha
Dhruv Chadha

Reputation: 1177

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

Upvotes: 0

Views: 7972

Answers (2)

Yilmaz
Yilmaz

Reputation: 49709

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.

Upvotes: 0

daniel aagentah
daniel aagentah

Reputation: 1702

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)

Upvotes: 1

Related Questions