E
E
ezpy2017-07-04 19:14:14
go
ezpy, 2017-07-04 19:14:14

Vuejs + golang how to connect to websocket?

Hello, there was a problem with sockets.
I don't quite understand what my problem is.
The two apps run on different ports, api (Golang app) on port :8081 and vuejs app in dev mode (vue-cli webpack-simple) on port :8080.
I'm trying to send a request from a vuejs application to ws://localhost:8081, but I get this error

WebSocket connection to 'ws://localhost:8081/ws' failed: Error during WebSocket handshake: Unexpected response code: 403

I am familiar with CORS, I use labstack echo.
Here is the code:
golang main.go:
package main

import (
  "fmt"

  "github.com/gorilla/websocket"
  "github.com/labstack/echo"
  "github.com/labstack/echo/middleware"
)

var (
  upgrader = websocket.Upgrader{}
)

func hello(c echo.Context) error {
  ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
  if err != nil {
    return err
  }
  defer ws.Close()

  for {
    // Write
    err := ws.WriteMessage(websocket.TextMessage, []byte("Hello, Client!"))
    if err != nil {
      c.Logger().Error(err)
    }

    // Read
    _, msg, err := ws.ReadMessage()
    if err != nil {
      c.Logger().Error(err)
    }
    fmt.Printf("%s\n", msg)
  }
}

func main() {
  e := echo.New()
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())

  e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins:     []string{"*"},
    AllowCredentials: true,
    AllowHeaders:     []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
  }))

  e.GET("/ws", hello)

  e.Logger.Fatal(e.Start(":8081"))
}

(The code is simple, but I'm still trying to solve the connection issue)
vuejs app:
export default {
    data: function () {
      return {
        seen: false,
        ws: null,
      };
    },
    created: function () {
      var self = this;
      this.ws = new WebSocket('ws://localhost:8081/ws');
      this.ws.addEventListener('message', function (e) {
        var msg = JSON.parse(e.data);
      });
      this.ws.onopen = function () {
        console.log('Connected')
      }

    },
........

It looks like you did everything right, but
7079bbd30f67426a99a95ee3d6a1021f.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hitakiri, 2017-07-18
@ezpy

When asked a similar question. Used this tutorial.

A
Alexander Fedotov, 2017-07-05
@orderbynull

Try to see an example here: https://github.com/orderbynull/lottip/blob/master/...
You may be starting the websocket server incorrectly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question