调用服务器时找不到socket.io

时间:2018-05-30 23:23:40

标签: javascript node.js sockets

我试图在Angular和Nodejs服务器上连接socket.io 在Angular中,我声明了一个新套接字并连接它

import * as io from 'socket.io-client';
...
@component
...
const socket = io.connect('http://localhost:3000');

在后端:server.js

const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.set('origins', 'http://localhost:4200');

var routes = require('./routes/routes')(io);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:4200");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
    res.header('Access-Control-Allow-Credentials', true);

    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
    );
    next();
});
io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    console.log("connectd");
});
app.use('/', routes);
var server = app.listen(3000, function (io) {
})

该应用正在编译并从服务器获取数据。但只有socket.io不起作用 我收到这个错误:

  

获取http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MEpN9Qy 404(未找到)

1 个答案:

答案 0 :(得分:1)

socket.io附加到http

var http = require('http').Server(app);
var io = require('socket.io')(http);

所以你必须使用:

http.listen(3000) 

而不是

app.listen(3000) // This will only start an express server

您的套接字服务器永远不会启动,这就是您获取404的原因,因为只有express正在运行。