首页 > 解决方案 > 无法从html中的表单获取数据

问题描述

我想把表单中的数据发布到服务器中,最后跳转到chat.html页面。客户资料如下

<form action="chat.html" method="POST">
                        <input
                            type="text"
                            name="username"
                            id="username"
                            placeholder="Enter username..."
                            required
                        />

                        <input
                        type="text"
                        name="room"
                        id="room2"
                        placeholder="Enter room name..."
                        required
                        disabled = "disabled"
                        />
...
</form>

服务器端

app.post("chat.html", (request, response) => {
  console.log(request.body);
});

我希望服务器可以接收到表单中的数据,客户端可以跳转到chat.html页面。但是,出现了无法 POST /chat.html的问题。我怎么能解决这个问题?我尝试使用

<form action="/chat" method="POST">

数据可以接收,但页面不能跳转。

标签: javascripthtmlnode.js

解决方案


您可以将表单操作更改为路线,并在后面使用相同的路线。

在表格中;

<form action="/chat" method="POST"> ...

后端;

// render the chat.html
app.get("/chat",(request,response)=>{ response.render("chat.html")});
// post request in /chat route
app.post("/chat", (request, response) => {console.log("form posted")});

推荐阅读