Rhushikesh
Rhushikesh

Reputation: 3700

AWS websocket throwing CORS error while connecting

I am working on the AWS WebSocket chat application using a serverless framework.

I have followed the this article to develop websocket api

but when I try consume those websocket in my angualar application its throwing error

from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

here is my chat module

mport { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { ChatService } from './chat.service';
const config: SocketIoConfig = { url: 'wss://xyz.execute-api.us-east-1.amazonaws.com/dev', options: {} };
const routes: Routes = [
  { path: 'chat', component: ChatComponent }
];
@NgModule({
  declarations: [ChatComponent],
  imports: [
    CommonModule, SocketIoModule.forRoot(config),
    RouterModule.forRoot(routes),

  ],
  providers: [ChatService],
  exports: [ChatComponent]
})
export class ChatModule { }

here is my chat service:

export class ChatService {

  constructor(private socket: Socket) { }
  sendMessage(msg: string) {
    this.socket.emit("sendMessage", msg);
  }
}

I have used the url which I got after sls deploy

enter image description here

Here is browser error:

enter image description here

Upvotes: 1

Views: 1639

Answers (1)

Atul Sharma
Atul Sharma

Reputation: 10655

Just add cors:true under function.events for all events to access them via cross origin in your serverless.yml file like :-

events:
      - websocket:
          route: $connect
          authorizer: authorizerFunc
          cors : true

and re-deploy the lambda.

Upvotes: 2

Related Questions