I am trying to establish a websocket connection between my angular(17) frontend and python backend for a chatbot.
For the client side, I am using the ngx-socket-io for websocket. Here is the relevant code for that.
This is the app.config.ts file. Herein, I am configuring the SocketIoModule as per the instructions given in ngx-socekt-io github page here – https://github.com/rodgc/ngx-socket-io/blob/master/README.md
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { routes } from './app.routes';
const config: SocketIoConfig = {
url: 'http://localhost:8765',
options: {}
};
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
importProvidersFrom(HttpClientModule),
importProvidersFrom(SocketIoModule.forRoot(config))
]
};
Here is the service that I created – following instruction from same github page.
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ChatService {
constructor(private socket: Socket) { }
sendMessage(msg: string){
console.log("Sending the message through a socket");
this.socket.emit('message', msg);
}
getMessage(){
return this.socket.fromEvent('message').pipe(map((data:any) => data.msg));
}
}
For the backend, I am using python websockets library.
Here is the simple server code.
import asyncio
import websockets
from chat import process_chat, agentExectuor
agentExectuor = agentExectuor()
async def hello(websocket, path):
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept',
'Access-Control-Allow-Credentials': 'true',
}
await websocket.prepare(websocket)
await websocket.send_headers(headers)
async for user_input in websocket:
print(str(user_input))
response = process_chat(agentExectuor, str(user_input))
await websocket.send(response)
async def main():
async with websockets.serve(hello, "localhost", 8765):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
When I run the frontend with ng serve, I can see a ws type packet which has response status code 101 meaning that protocol change has occurred and it seems as if the connection is established. Here is the snapshot of that. I am very sorry if I am misconstruing this.
A snapshot of this is attached.
ws packet
Why does this have url as ws://localhost:4200? At 4200, my angular frontend is running. Shouldn’t this be ws://localhost:8765?
Now, console gives a cors error –
Access to XMLHttpRequest at 'http://localhost:8765/socket.io/?EIO=4&transport=polling&t=P0gBFXz' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
After cors error, I see a get request whose response packet is like this. Packet which is a response from a get request to this url – http://localhost:8765/socket.io/?EIO=4&transport=polling&t=P0gBFXz.
This one has 426(upgrade required). A snapshot of this is attached as well.
Upgrade required packet error
I have tried changing url in my config file to ws instead of http. It didn’t help.
I have also tried setting particular cors origin to be localhost:4200 but that did not work either.
DataBayesWizard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.