javascript - 重定向到 Node js Express 中的新页面?

标签 javascript node.js express socket.io

我正在使用 socket.io 在 Node js 中创建一个聊天应用程序。当新用户登录 localhost:3000 时,会给出一个表单,您可以在其中输入您的姓名和要进入的房间。按下提交按钮后,如何将此用户重定向到适当的房间? 当连接到 localhost:3000 时,我的服务器默认显示 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");
});

login.html 中的表单 -

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

最佳答案

您可以像这样使用 res.redirect([status,] path) :

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

这将使用指定的 HTTP 状态代码状态重定向到给定的 URL。如果未指定状态代码,则状态代码默认为 302(这在大多数用例中都可以)

关于javascript - 重定向到 Node js Express 中的新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015131/

相关文章:

javascript - 是否有任何技术或插件来照亮元素(按钮)?

javascript - 动态加载图像,错误时中断循环

node.js - "Res.redirect"从 React 到 Node 进行 Ajax 调用时不工作?

javascript - Service Worker 注册错误 : Unsupported MIME type ('text/html' )

node.js - Express 中的 404 后备路线

javascript - ember 属性在 View 中不可用,仅 ID

javascript - PHP 或 Javascript - 查找特定字符串

javascript - 如何 promise 我编写的简单异步函数?

javascript - SubscriptionConfirmation 请求中的 Token 或 SubscribeUrl 在哪里?

node.js - Node.js 的 ntwitter 模块出错