如何在 Next.js 中实现 React hook Socketio [英] How To Implement React hook Socketio in Next.js

查看:154
本文介绍了如何在 Next.js 中实现 React hook Socketio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从谷歌找到一种方法,但结果可以保持不变

I have tried to find a way from Google but the results can remain the same

http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MnHYrvR

我试试这个 wan medium 试试其他方法,结果保持不变

i try this wan medium try other ways, the results remain the same

而对于我尝试过的前端,钩子组件内和作用域外的socket io,结果都一样

and for the front end I have tried, socket io inside the hook component and outside the scope, the results remain the same

http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MnHYrvR

这是我来自服务器的代码:

this is my code from server:

app.prepare().then(() => {
    const server    = express();
    const setServer = require('http').Server(server);
    const io        = require('socket.io')(setServer)

    server.use(bodyParser.json());
    server.use(cookieParser());

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

        socket.emit('now', {
            message: 'zeit'
        })
    })


    server.use(routers)

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    server.use( (err, req, res, next) => {
        console.log(err)
        if(err.name === 'Error'){
            res.status(401).send({
                title: 'error',
                detail: 'Unauthorized Access!'
            })
        }
    })

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://heroku:${port}`)
    })
})
.catch(ex => {
    console.error(ex.stack);
    process.exit(1);
});

来自前端:

//at the top of function
const io = require('socket.io-client');
const socket = io.connect('http://localhost:8000');
console.log('socket', socket);

//in use effect
useEffect(() =>{
        socket.on('now', message => {
            console.log('message', meesage);
        })
    })

请帮忙

推荐答案

虽然我没有使用 Next.js,但我有一个与 Express.js 类似的设置可能会帮助您解决问题...

Although I am not using Next.js, I have a similar setup with Express.js that might help you with your problem...

在我的 Node.js 端,我有以下设置:

On my Node.js side I have the following setup:

const app = require('express')()
const server = require('http').createServer(app)
const io = require('socket.io')(server)

// ...

io.sockets.on('connection', () => {
  console.log(`Client with ID of ${socket.id} connected!`)

  io.sockets.emit('SOME_EVENT', 'HelloWorld')
})

然后,我的 React 前端看起来像这样:

Then, my frontend with React looks like this:

import React from 'react'
import io from 'socket.io-client'

function useSocket(url) {
  const [socket, setSocket] = useState(null)

  useEffect(() => {
    const socketIo = io(url)

    setSocket(socketIo)

    function cleanup() {
      socketIo.disconnect()
    }
    return cleanup

    // should only run once and not on every re-render,
    // so pass an empty array
  }, [])

  return socket
}

function App() {
  const socket = useSocket('http://127.0.0.1:9080')

  useEffect(() => {
    function handleEvent(payload) {
      console.log(payload) 
      // HelloWorld
    }
    if (socket) {
      socket.on('SOME_EVENT', handleEvent)
    }
  }, [socket])

  return (...)
}

<小时>

此外,我在使用 socket.io 时看到的一个常见错误如下:


Also, one common error that I am seeing when working with socket.io is the following:

Cross-Origin Request Blocked: The Same Origin Policy disallows 
reading the remote resource at 
http://127.0.0.1:9080/socket.io/?EIO=3&transport=polling&t=MnH-W4S.
(Reason: CORS request did not succeed).

这是由于在套接字管理器创建过程中作为参数提供的 URL 不正确:

This is due an incorrect URL that's provided as a parameter in the socket manager creation process:

const socket = io('http://localhost');

因此,请仔细检查您提供的地址是否正确.如果您在 now 上提供应用程序并通过 now.sh URL 访问它,但提供 http://localhost 作为您的 URL参数,那么它将不起作用.

So just double check that the address you're providing is correct. If you're serving your application on now and accessing it through a now.sh URL, but providing http://localhost as your URL parameter, then it won't work.

这篇关于如何在 Next.js 中实现 React hook Socketio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆