简体   繁体   English

将 socket.io(^3.0.0) 与 Strapi Server("3.2.5") CORS 错误集成

[英]Integrating socket.io(^3.0.0) with Strapi Server("3.2.5") CORS Error

I'm trying to build a simple chat app.我正在尝试构建一个简单的聊天应用程序。 I'm using create-react-app for the front-end, and I'm trying to integrate socket.io with Strapi server.我在前端使用 create-react-app,我正在尝试将 socket.io 与 Strapi 服务器集成。 My create-react-app server is running on Port 3000, while my Strapi local server is running on port 1337.我的 create-react-app 服务器在端口 3000 上运行,而我的 Strapi 本地服务器在端口 1337 上运行。

I've used this command to install starpi yarn create strapi-app chat-app and manually selected mongodb as database.我已经使用这个命令来安装 starpi yarn create strapi-app chat-app并手动选择mongodb作为数据库。

Receiving this error in the React app:在 React 应用程序中收到此错误:

react-socket-cors-err

Code代码

On my React component, I have this:在我的 React 组件上,我有这个:

import io from 'socket.io-client';
const socket = io('http://localhost:1337');

 const handleClick = () => {        
        const username = props.username;
        socket.emit("sendMessage", {
            chatMessage,
            username
        })
    }

In the Strapi backend, inside ./config/functions/bootstrap.js在 Strapi 后端,在./config/functions/bootstrap.js

module.exports = async () => {
    process.nextTick(() => {
        var io = require('socket.io')(strapi.server);

        strapi.io.on('connection', async function(socket) {

            socket.on('sendMessage', (msg) => {
                console.log("msg is", msg)
            })
            socket.on('disconnect', () =>{
                console.log('a user disconnected')
            });
        });
         strapi.io = io;
      })
};

I know to solve this cors error inside node app using cors module and use it like app.use(cors()) But not sure how I resolve this in case of strapi?我知道使用 cors 模块在节点应用程序中解决这个cors错误,并像app.use(cors())一样使用它,但不知道在 Strapi 的情况下我如何解决这个问题?

I followed this thread and tried some of the workarounds, but none of them seem to work.我遵循了这个线程并尝试了一些解决方法,但它们似乎都不起作用。 How do I resolve this issue?我该如何解决这个问题?

So I resolved this issue by providing cors object to my socket.io.所以我通过向 socket.io 提供 cors 对象来解决这个问题。 Option origins have been replaced with cors in the lastest version of socket.io(3.0.0)选项origins已在最新版本的 socket.io(3.0.0) 中替换为cors

    var io = require('socket.io')(strapi.server, {
            cors: {
              origin: "http://localhost:3000",
              methods: ["GET", "POST"],
              allowedHeaders: ["my-custom-header"],
              credentials: true
            }
   });

Checkout the socket migration guide for more info:查看套接字迁移指南以获取更多信息:

https://socket.io/docs/migrating-from-2-x-to-3-0/ https://socket.io/docs/migrating-from-2-x-to-3-0/

I'm able to receive messages in the backend now.我现在可以在后端接收消息了。 Thanks, Arya!谢谢,艾莉亚!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM