Javascript 得到http://localhost:3306/socket.io/?EIO=3&运输=投票及;t=NQfLxAy net::错误\u无效\u HTTP\u响应

Javascript 得到http://localhost:3306/socket.io/?EIO=3&运输=投票及;t=NQfLxAy net::错误\u无效\u HTTP\u响应,javascript,html,node.js,Javascript,Html,Node.js,我正在使用Node.js构建一个实时聊天室。所以现在我只想在控制台中显示用户输入的名称。但它不能做到这一点。请帮我这个忙,我会非常感激的 index.php <!-- include jquery and socket IO --> <script src="js/jquery.js"></script> <script src="js/socket.io.js"></script> &

我正在使用Node.js构建一个实时聊天室。所以现在我只想在控制台中显示用户输入的名称。但它不能做到这一点。请帮我这个忙,我会非常感激的

index.php

    <!-- include jquery and socket IO -->
<script src="js/jquery.js"></script>
<script src="js/socket.io.js"></script>

<!-- create a form to enter username -->
<form onsubmit="return enterName();">
    <input type="text" name="name" id="name" placeholder="Enter name">
    <input type="submit" name="submit">
</form>

<script>
    res.setHeader('Access-Control-Allow-Origin', "localhost:3000");
    //creating io instance
    var socket = io("http://localhost:3000");

    function enterName(){
        //get username
        var name = document.getElementById("name").value;

        //send it to server
        socket.emit("user_connected", name);

        //prevent the form from submiting
        return false;
    }

    //listen from server
    socket.on("user_connected", function (username){
        console.log(username);
    });
</script>
问题出在index.php中。请让我知道你认为问题可能在哪里,如果可能的话,你也可以尝试我的index.php并编辑它,让它工作。非常感谢!:)


似乎正在使用不同的端口。

客户端连接已经有一个本机事件,您应该使用它,而不是引入另一个事件来完成相同的工作。socket.on('connect')。侦听传入的连接服务器。打开('connection')嘿!谢谢你的观察。我在做试错的时候改变了它,但我忘了注意到这一点。但是,控制台上现在仍显示以下错误“从源站“”访问“”处的XMLHttpRequest已被CORS策略阻止:请求的资源上不存在“访问控制允许源站”标头。失败:3000/socket.io/?EIO=3&transport=polling&t=NQfPndV:1以加载资源:net::ERR\u失败”必须在express服务器上启用CORS。用这个来做:编辑:我的坏。您正在使用http。您必须随响应一起发送访问控制标头。有很多方法可以做到这一点,但最简单的方法是:
res.setHeader('Access-Control-Allow-Origin',“您的地址”)
Tnx!我希望这能奏效。编辑:哦,我刚刚读了你编辑的部分。让我试试我的地址是什么?为了确认一下,你能举个例子吗?在你的例子中
localhost:3000
    //creating express instance
var express = require("express");
var app = express();

//creating http instance
var http = require("http").createServer(app);

//creating socket io instance
var io = require("socket.io")(http);

io.on("connection", function (socket){
    console.log("User connected", socket.id);

    // attach incoming listener for new user
    socket.on("user_connected", function (username) {
        // save in array
        users[username] = socket.id;

        // socket ID will be used to send message to individual person

        // notify all connected clients
        io.emit("user_connected", username);
    });
});

//start the server
http.listen(3000, function(){
    console.log("Server started");
});
http.listen(3000, function(){
    console.log("Server started");
});
var socket = io("http://localhost:3306");