【发布时间】: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 并删除这些空格?从“
<input type = "TEXT" class = "CHECK"”到“<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