Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Real time chat with server in a different IP address #155

Open
grrbm opened this issue May 31, 2024 · 2 comments
Open

Real time chat with server in a different IP address #155

grrbm opened this issue May 31, 2024 · 2 comments

Comments

@grrbm
Copy link

grrbm commented May 31, 2024

hey Francisco, I'm trying to implement a socket.io real-time chat, similar to your tutorial. If I do this:

curl "<the server URL>/socket.io/?EIO=4&transport=polling"

it returns correctly, so the backend is working. but I do get CORS error when trying to have my frontend make an API call to the backend, which is in a different port.

I'm not sure what this CORS error is about; I already have the http://localhost:3000 (frontend) route whitelisted using the express cors package. (And it should be working since my other frontend api calls work)

@grrbm
Copy link
Author

grrbm commented May 31, 2024

So, I think I tracked down the reason for the CORS error, and made a temporary fix for it.

Basically we don't have a way of passing cors configuration to socket.io: https://socket.io/docs/v4/handling-cors/

I went here and hardcoded the socket.io CORS options:

   ctx.io = socketIO(ctx.server, {...ctx.options.socket,  cors: {
      origin: "http://localhost:3000",
      methods: ["GET", "POST"],
      allowedHeaders: ["Content-Type"],
      credentials: true,
    },});

@grrbm
Copy link
Author

grrbm commented May 31, 2024

It's actually a super easy fix, we just have to add cors: {} to the list of options here, then we can pass the cors options for the socket io instance when instantiating the server:

server(
  {
    port,
    socket: {
      cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"],
        allowedHeaders: ["Content-Type"],
        credentials: true,
      },
    },
  },
  cors,
  [
    get("/", (ctx) => render("index.html")),
    socket("connect", updateCounter),
    socket("disconnect", updateCounter),
    socket("message", sendMessage),
  ]
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant