Использование ngrok с WebSocket (или socket.io)
Я делаю сайт с крестиками-ноликами и для этого хочу использовать socket.io и ngrok, но когда я захожу на сайт web-socket не работает
server:
const express = require('express')
const http = require('http')
const { Server } = require('socket.io')
const cors = require('cors')
const app = express()
app.use(
cors({
origin: '*',
})
)
app.get('/', (req, res) => {
res.send('Привет, мир!')
console.log('res has been sent!')
})
const server = http.createServer(app)
const PORT = 3000
server.listen(PORT, () => {
console.log('Sever has started!')
})
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
})
io.on('connection', socket => {
console.log('A user connected')
socket.on('findGame', data => {
console.log(`Someone is finding a game! ${data}`)
})
})
client:
import { useState } from 'react'
import io from 'socket.io-client'
import styles from './Game.module.scss'
const socket = io.connect('https://b76f-93-171-102-69.ngrok-free.app ')
export function Game() {
const [cells, setCells] = useState(['', '', '', '', '', '', '', '', ''])
function changeCell(id) {
const newCells = [...cells]
newCells[id] = 'cross'
setCells(newCells)
}
const cellParams = {
cross: { style: styles.cross, path: '/src/assets/cross.svg' },
circle: { style: styles.circle, path: '/src/assets/circle.svg' },
}
return (
<div className={styles.game}>
<div className={styles.gameInfo}>
<h1>You Won!</h1>
<p>Congratulations</p>
</div>
<div className={styles.gameField}>
{cells.map((cell, index) => {
if (!(cell in cellParams))
return (
<button
className={styles.cell}
key={index}
onClick={() => changeCell(index)}
></button>
)
const { style, path } = cellParams[cell]
return (
<button className={`${styles.cell} ${style}`} key={index}>
<img src={path} alt='' />
</button>
)
})}
</div>
<button
className={styles.gameButton}
onClick={() => socket.emit('findGame', 'Привет')}
>
<img src='/src/assets/reset.svg' alt='' />
Find a game
</button>
</div>
)
}