Socket.IO 404在本地工作,但在通过Netlify部署时无法工作

时间:2019-05-10 22:43:44

标签: javascript node.js express socket.io

Socket.IO在本地工作,但在通过Netlify部署时无法工作 请原谅我的代码,我是node.js等的新手。

这是我得到的错误: 无法加载资源:服务器响应状态为404()(socket.io,第0行)

客户:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>
function syncObj() { 
var socket = io.connect() 
socket.emit('sync', `${objId}`)}
// Listen for events
function syncComplete() {
var socket = io.connect()
socket.on('sync', function (data) {
objId = data
noti5()
document.getElementById("note4").style.display = "none";
document.getElementById("note6").style.display = "none";
// What do do when sync is complete
// Say Something
// Refresh Screen
})
}

//Server:
const express = require('express');
const opn = require('opn');
const app = express();
const port = 5000
var socket = require('socket.io')
const cors = require("cors")

function allowCrossDomain(req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH,   DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,   Content-Type, Accept");
next()}
app.use(allowCrossDomain)
app.use(cors())
app.use('/', express.static(__dirname + '/public'))

var server = app.listen(port, function () {
console.log('listening to request on port 5000');
opn(`http://localhost:${port}`);
});

// Socket Setup
var io = socket(server);
io.on('connection', function (socket) {
console.log('made socket connection', socket.id)

socket.on("sync", function(data){
io.sockets.emit('sync', data)
})
})

在本地完美工作。请帮忙。

1 个答案:

答案 0 :(得分:0)

您应该在io.connect(url here)

中提及您的网址

尝试一下:

var socket = io('/');

如果我们使用'/'代替url,它将自动获取url(如果它是localhost或在其他ip上托管)。您还可以在此处提及您的完整url。

var socket = io('http://localhost:port')
//or something else

这里是一个例子:

服务器:

const express = require('express');
const app = express();
const socket = require('socket.io');
const port = process.env.PORT || 8080;
//starting the server
const server = app.listen(port,() => {console.log("server running")});

//connecting socket to the server
const io = socket(server);
io.set('transports', ['websocket']);

io.on('connection',socket =>{
// your code here
}

客户端:

var socket = io('/',{transports: ['websocket'],upgrade:false});

//on connection 
socket.on('connect',data =>{
//logic here
}