【问题标题】:Why is form data not being sent to the server?为什么表单数据没有发送到服务器?
【发布时间】:2022-02-08 15:06:49
【问题描述】:

我正在实现一个聊天,创建一个注册窗口,并且需要将表单中的数据发送到服务器,然后将其发送到客户端以显示在客户端列表中。但是由于某种原因,表格中的数据没有出现,这是什么问题?这是 index.html 的表格:

<form class = "FORM" action="/" method="post">
  <label>Username</label><br>
  <input type = "TEXT" class = "CHECK" autocomplete="off" name="Username">
  <button type = "submit" class="BTN" onclick="redirect()">Send</button>
</form>

这里是 express index.js 上的服务器

const express = require('express');
const app = express();
const db = require('./database/database'); // подключаемся к бд
const urlencodedParser = express.urlencoded({extended: false});
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

const port = 3000;
let id = 0;
let users = {};

app.use(express.static(__dirname));

app.get('/', (request, response ) => {
    response.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {

    app.post("/", urlencodedParser, function (request, response) {
        if(!request.body) return response.sendStatus(400);
        console.log(request.body);
        //response.send(`${request.body.userName} - ${request.body.userAge}`);
    });
.....

为什么数据没有从表单传到服务器?

【问题讨论】:

  • 您是否尝试过重新格式化您的 html 并删除这些空格?从“&lt;input type = "TEXT" class = "CHECK"”到“&lt;input type="TEXT" class="CHECK"”(对于每个 html 元素)?
  • 你为什么要在套接字连接处理程序内部注册你的app.post()处理程序?把它移开,我怀疑这一切都会开始工作。此外,您的 app.get("/") 是多余的,因为 express.static() 已经在为您的 index.html 文件提供服务
  • @Kristian 在= 周围有空格是允许的。
  • redirect函数的内容是什么?它会阻止默认吗?
  • 不幸的是,移动过去的套接字和删除空格都没有帮助。当单击按钮时,函数 redirect() 将用户重定向到另一个页面(并且表单数据本身是通过 localStorage 传递的,这对我来说似乎是错误的)。常量重定向 = ()=> { window.location = 'client/chat.html' }

标签: javascript node.js


【解决方案1】:

您必须向端点发出 axios 发布请求。

如果您使用的是原生 javascript,您还需要在表单中添加事件监听器。

const form = document.getElementsByClassName("FORM");
form.addEventListener("submit", (event) => {
event.preventDefault();
const userName = event.target.Username.value;
if (!userName) alert("Username is required");
else {
    axios
        .post(
            "http://localhost:3000/", {
            userName
        })
    .then((response) => {
        console.log(response.data);

        /*depending on what response you get from the server, 
you may want to use .map() method to display all the usernames*/
    })
    .catch((error) => console.log(error));
    event.target.reset();
 }
})

【讨论】:

  • 这是绝对错误的。 HTML 表单完全能够在没有 JavaScript 的情况下提交数据
猜你喜欢
  • 2021-04-28
  • 2019-05-27
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多