【问题标题】:AWS websocket throwing CORS error while connectingAWS websocket在连接时抛出CORS错误
【发布时间】:2020-08-10 07:21:48
【问题描述】:

我正在使用无服务器框架开发 AWS WebSocket 聊天应用程序。

我已经关注this article开发websocket api

但是当我尝试在我的角度应用程序中使用这些 websocket 时,它会抛出错误

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

这是我的聊天模块

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 { }

这是我的聊天服务:

export class ChatService {

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

我使用了sls deploy后得到的url

这是浏览器错误:

【问题讨论】:

  • 这里有 AWS Lambda 函数,是吗?您是否检查过 CloudWatch Logs 是否存在 Lambda 函数中的错误?
  • @Rhushikesh 嗨,你能解决这个问题吗?

标签: amazon-web-services websocket cors serverless-framework


【解决方案1】:

只需在function.events 下添加cors:true 即可让所有事件通过serverless.yml 文件中的交叉源访问它们,例如:-

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

并重新部署 lambda。

【讨论】:

  • cors 用于 http 调用,但我仍然添加但它不起作用
猜你喜欢
  • 2019-06-11
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 2019-03-21
相关资源
最近更新 更多