Issue
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NQb0Bxp' from origin 'http://localhost:8100' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
in Node js (Backend)
var express = require('express');
var app = express();
const cors = require('cors');
app.use(cors());
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var server = require('http').createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:8100",
methods: ["GET", "POST"],
}
});
io.on('connection',function(socket){
console.log("A user connected");
// socket.emit('test event','my connection');
socket.on('test event',(data)=>{
console.log(data);
socket.emit('test event','my connection');
})
})
// console.log(app)
server.listen(3000,()=>{
console.log("socket io server is listening on port 3000");
});
in angular
websocker.service.ts
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
socket:any;
readonly url = "ws://localhost:3000";
constructor() {
console.log(io,"io")
this.socket = io.connect(this.url,{});
}
listen(eventName:string){
return new Observable((subscriber)=>{
this.socket.on(eventName , (data)=>{
subscriber.next(data);
});
})
}
emit(eventName:string,data:any){
this.socket.emit(eventName,data);
}
}
Solution
Socket.io (3.x) the migration documents are fairly helpful.
const io = require("socket.io")(httpServer, {
cors: {
origin: "https://example.com",
methods: ["GET", "POST"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
Answered By - Devesh Goyal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.