Answer the question
In order to leave comments, you need to log in
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
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"))
}
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')
}
},
........
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question