javascript - 如何修复套接字 io 中的 400 错误错误请求?
问题描述
我有一个前端应用程序(VUE JS)
我有一个后端(Nest JS)
Vue JS 应用程序使用 vue-socket.io-extended 库通过 websockets 从后端获取数据当 Vue JS 应用程序启动时,我在浏览器中看到错误:
polling-xhr.js?d33e:229 POST http://localhost:11050/socket.io/?EIO=4&transport=polling&t=NMXgCF1 400(错误请求)
我该如何解决这个错误?
我认为它没有与库连接,我只尝试了 socket io 库,结果是一样的。
服务器正在工作,因为它发送日志并显示谁已连接:
服务器(Nest JS) main.ts 文件:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(11050);
}
bootstrap();
应用程序网关:
@WebSocketGateway()
export class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
private logger: Logger = new Logger('AppGatway');
@SubscribeMessage('msgToServer')
handleMessage(client: Socket, text: string): WsResponse<string> {
return { event: 'msgToClient', data: text };
}
afterInit(server: Server) {
this.logger.log('Initialised!');
}
handleConnection(client: Socket, ...args: any[]): any {
this.logger.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket): any {
this.logger.log(`Client disconnected: ${client.id}`);
}
}
前端(Vue JS):
import VueSocketIOExt from "vue-socket.io-extended";
import Vue from "vue";
import io from "socket.io-client";
const socket = io("http://localhost:11050/");
Vue.use(VueSocketIOExt, socket);
data: () => ({
socket: null,
connection: null,
sockets: {
connect() {
console.log("socket connected");
},
},
}
解决方案
在服务器端尝试以下配置
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:8100",
methods: ["GET", "POST"],
transports: ['websocket', 'polling'],
credentials: true
},
allowEIO3: true
});
推荐阅读
- c# - 当我单击 ListBoxItem 时,如何使 StackPanel 滑到一边
- javascript - Mongoose 填充不填充数组
- javascript - HTML5 - html、前缀和元相关
- sql - SQL - 复杂条件
- go - 在 Go 中将 2^8 位表示转换为 BigInteger
- spring - 无法使用 JUnit 测试弹簧注入
- javascript - 条件为真时链式承诺
- php - 如何使 moloquent 的 embedsOne 关系起作用?
- ruby-on-rails - Bootstrap 4 药丸标签不会加载内容——Rails 4
- python - 在 on_message 函数外部调用时的变量无法在函数内部引用