I've deployed my NodeJs socket server with pm2 and apache, and getting the error No 'Access-Control-Allow-Origin' header is present on the requested resource. when called from my angular app. This issue appears only when I use the domain name pointed to the process. When using http://<ip_address>:<port>, it's working.
Angular code
setupScheduleSocket(){
this.scheduleSocket = io.connect(environment.SCHEDULE_SOCKET);
this.scheduleSocket.on('connect', ()=>{
console.log("connected", environment.SCHEDULE_SOCKET);
});
this.scheduleSocket.on('connect_error', () => {
console.log('connection error');
});
this.scheduleSocket.on('disconnect', () => {
console.log('disconnected');
});
}
NodeJs
const https = require('http');
//const server = https.createServer();
const socketIO = require('socket.io');
const server = https.createServer((req, res) => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000,
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type',
'Access-Control-Allow-Credentials': true
};
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
if (['GET', 'POST'].indexOf(req.method) > -1) {
res.writeHead(200, headers);
res.end('Hello World');
return;
}
res.writeHead(405, headers);
res.end(`${req.method} is not allowed for the request.`);
});
/* socket */
io = socketIO(server);
io.on('connection', (socket) => {
console.log("connected");
socket.on('refresh-user', (data)=>{
io.emit('refresh-user', data);
console.log(data);
});
});
server.listen(6900, ()=> {
console.log('listening on 6900');
});