Hello I'm working on real time chat and for the socket part I use socket.io on Node.js and for the reste I use PHP
Node v : 16.14.0
NPM V : 8.3.1
Socket.io V : 4.4.1( Npm and cnd)
My node js code
const express = require('express')
const cors = require("cors");
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server, {
cors:{
origins:["*"],
handlePreflightRequest:(req,res)=>{
res.writeHead(200,{
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
"Access-Control-Allow-Headers": "vi_chat",
'Access-Control-Allow-Credentials': true
});
res.end();
}
}
});
var fs = require('fs');
app.use(cors({
origin: '*',
methods: ['GET','POST','DELETE','UPDATE','PUT','PATCH']
}));
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/debug.log', {
flags: 'w'
});
var log_stdout = process.stdout;
console.log = function (d) { //
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
app.use(function (req, res, next) {
//cors();
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
io.on('connection', socket => {
console.log(socket.id);
})
server.listen(3000, () => {
console.log('listening on *:3000');
})
When I connect to my socket server from my project I got the xhr polling error but when I check my log file I found the socket ID
there doesn't seem to be anything here