简体   繁体   English

重定向到节点js express中的新页面?

[英]Redirect to a new page in node js express?

I am creating a chat app in node js using socket.io. 我正在使用socket.io在节点js中创建一个聊天应用程序。 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. 当新用户登录到localhost:3000时,将显示一个表单,您可以在其中输入您的名称和要输入的房间。 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. 当localhost:3000连接到我的服务器时,由dafault显示的login.html,我希望单击提交后发出新请求,以便第二个app.get可以为其提供服务。

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 - 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: 您可以像这样使用res.redirect([status,] path):

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

This will redirect to the given URL using the specified HTTP status code status. 这将使用指定的HTTP状态代码状态重定向到给定的URL。 If no status code is specified, the status code defaults to 302 (which is fine in most use cases) 如果未指定状态码,则状态码默认为302(在大多数情况下都可以)

When the form is submit, the browser turns that form into a HTTP request, using the inputs as parameters for query string. 提交表单后,浏览器使用输入作为查询字符串的参数,将该表单转换为HTTP请求。 let's say you have a form like this in login.html: 假设您在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. 单击它后,此html页面将使用2个字符串参数重定向到/ chat route。 your url will be like this: 您的网址将如下所示:

http://localhost:3000/chat.html?username=yourUserName&room=yourRoom 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. 现在,您需要创建一个chat.html,提交后将显示此页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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