无法通过SocketIO连接VueJS和NodeJS

问题描述 投票:0回答:0

无法与前端的VueJS 和NodeJS(SocketIO)进行简单的连接。我主要关注 SocketIO 的官方教程。

节点:

const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require("socket.io")
const io = new Server({
    server,
    cors: {
        origin: "http://localhost:8080"
    }
})

io.on('connection', socket => {
    console.log('New connection...')    
})

app.listen(process.env.PORT, () => {
    console.log('Server started...')
})

文件 socket.js(在 Vue 根项目文件夹中):

import { reactive } from "vue"
import { io } from "socket.io-client"

export const state = reactive({
  connected: false
})

const URL = "http://localhost:3000"

export const socket = io(URL)

socket.on("connection", () => {
  state.connected = true
})

VueJS 组件:

<template>
    <button @click="connect()">Connect</button>
</template>

<script>
import { socket } from "@/socket"

methods: {      
    connect() {
        socket.connect()
    }
}
</script>

不管怎样,都有一个 404 响应的循环,“无法获取/socket.io/”,点击按钮也没有任何不同。

为什么连接不工作?

node.js vue.js express socket.io connect
© www.soinside.com 2019 - 2024. All rights reserved.