Iris: Error cors with socket IO

Created on 20 Jul 2018  ·  13Comments  ·  Source: kataras/iris

Hello,

I need help..I build mobile apps using ionic and socket IO..

I use iris for my api and use socket io. The library I use for socket io is from iris cobtrib..
When I run in device, its running well but when I run in browser socket io cannot connect because cors.

I do the same thing using express js and running well.in browser and device.

What should I do for the cors? Because I already do everything but nothing going well. I really need to solve this because if I can't, I must move to express js.

Thank you

support

Most helpful comment

@vincentri app.Run(...,iris.WithoutPathCorrection) will fix that for you, and guys... it has nothing to do with cors or to a proxy system, it wasn't hard to understand but when you don't read the docs you will always wait for somebody else to fill the gap for you... express js will give you more problems than solutions my dear, this is why this framework was created/invented at the first place.

All 13 comments

Cors is just a set of headers based on your needs it is not Iris vs express.js, it's general web specification and practises, for example:

app.AllowMethods(iris.MethodOptions)
app.Use(func(ctx iris.Context){
    ctx.Header("Access-Control-Allow-Origin", "*")
    ctx.Header("Access-Control-Request-Headers","Accept,content-type,X-Requested-With,Content-Length,Accept-Encoding,X-CSRF-Token,Authorization,token")
    ctx.Header("Access-Control-Request-Method","*")
    // ctx.Header("Access-Control-Expose-Headers","token")
    ctx.Next()
})
// your handlers here

If the above does not work for you I will need to see an example of your backend code for the endpoints, you can also star our repository if you like iris and its almost real-time support

Hello kataras,

here is my code:

package main

import (
CO "echo-pos/config"
CA "echo-pos/controllers/backend"
CF "echo-pos/controllers/frontend"
MD "echo-pos/middleware"
"log"
"os"

"github.com/googollee/go-socket.io"
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris"
"github.com/kataras/iris/middleware/recover"

)

func main() {
app := iris.New()

crs := cors.New(cors.Options{
    AllowedOrigins: []string{"*"},
    AllowedMethods: []string{"GET", "HEAD", "POST", "PUT", "OPTIONS", "DELETE"},
    AllowedHeaders: []string{"Accept", "content-type", "X-Requested-With", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Screen"},
    // AllowCredentials: true,
})

app.Use(recover.New())
app.Use(crs)
CO.Init()

app.RegisterView(iris.HTML("./views", ".html"))
app.StaticWeb("/public", "./public")

server, err := socketio.NewServer(nil)
if err != nil {
    log.Fatal(err)
}
server.On("connection", func(so socketio.Socket) {
    log.Println("on connection")
    so.Join("chat")
    so.On("chat message", func(msg string) {
        log.Println("emit:", so.Emit("chat message", msg))
        so.BroadcastTo("chat", "chat message", msg)
    })
    so.On("disconnection", func() {
        log.Println("on disconnect")
    })
})
server.On("error", func(so socketio.Socket, err error) {
    log.Println("error:", err)
})
app.Any("/socket.io/", crs, iris.FromStd(server))
app.Any("/socket.io/{p:path}", crs, iris.FromStd(server))

app.AllowMethods(iris.MethodOptions)
app.Use(func(ctx iris.Context) {
    ctx.Header("Access-Control-Allow-Origin", "*")
    ctx.Header("Access-Control-Request-Headers", "Accept,content-type,X-Requested-With,Content-Length,Accept-Encoding,X-CSRF-Token,Authorization,token")
    ctx.Header("Access-Control-Request-Method", "*")
    // ctx.Header("Access-Control-Expose-Headers","token")
    ctx.Next()
})
app.Run(
    iris.Addr(os.Getenv("PORT")),
    iris.WithoutVersionChecker,
    iris.WithoutServerError(iris.ErrServerClosed),
    iris.WithOptimizations, // enables faster json serialization and more
)

}


your above solution is not work.

here is the error:
websocket.js:112 WebSocket connection to 'ws://192.168.1.104:3000/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 301

but when I use express js, there is no error..Something must be wrong with the iris back end..

unexpected response code: 301 means "redirect". Check console log and you will see the location it is redirecting and then you can debug further.

@rebootcode yes..how to solve it?because when I use express js, it's running well.without redirect..

@vincentri - this error could be due to empty header sent for WebSocket.

Just add the response headers: Host, Connection, and Upgrade.

are you using any reverse proxy?

@rebootcode so i must add host connection and upgrade?

No I dont use reverse proxy..I will try again tonight..

It's so strange because I tried with express and working well..

Nodejs with express does automatically for you. To test this you, you can run your app inside reverse proxy of Caddy and use websocket module to get it working.

Good luck :)

Hmm, i think i will use express js for this case because it's very hard to config this..

It is not, You will anyhow use "reverse proxy", either it be "nginx" or "caddy" or any other, and when you will use reverse proxy, they will do it for you just like how expressjs is doing it for you.

You will either have to manually or let reverse proxy do it for you "to add the response headers: Host, Connection, and Upgrade."

@vincentri app.Run(...,iris.WithoutPathCorrection) will fix that for you, and guys... it has nothing to do with cors or to a proxy system, it wasn't hard to understand but when you don't read the docs you will always wait for somebody else to fill the gap for you... express js will give you more problems than solutions my dear, this is why this framework was created/invented at the first place.

Hello @kataras ..Thank yoou for the support.. work now..hehe

@vincentri
Did you solve the problem? How to solve it?

Was this page helpful?
0 / 5 - 0 ratings