0

I'm trying to serve multiple files with Echo, but it doesn't work every time. The api code looks like this:

package main

import (
    "github.com/labstack/echo"

    "net/http"
)

func main() {
    e := echo.New();

    e.GET("/", home);

    e.File("/data1", "assets/data1.csv");

    e.File("/data2", "assets/data2.csv");

    e.Logger.Fatal(e.Start(":4243"));
}

func home(c echo.Context) error {
  return c.String(http.StatusOK, "Are you lost?");
}

To be precise, it does work for the very first file fetching, but then keeps failing for any subsequent calls (be them file fetching or more "classic" calls). The error message is a tad different for each browser:

In Chrome:

SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Bearer {the_entire_content_of_the_first_fetched_file}' is not a valid HTTP header field value.

In Firefox:

SyntaxError: An invalid or illegal string was specified

In Edge, simply:

SyntaxError

Tried activating CORS, nothing changed.

Looks to work pretty well with Postman. Maybe it's a problem with how I do fetch my data in my application?

If you need perhaps a bit more information, this thread is directly related to my previous one (Vuejs with axios request in vuex store: can't make more than one request, why?), but I didn't want to mix them up, as I don't know yet if I'm mistaken in my Vue code or my Echo one...

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

3 Answers3

5

If you would like to delivery files from certain directory. You can do following ways:

e.Use(middleware.Static("/path/to/directory"))

OR

fs := http.FileServer(http.Dir("/path/to/directory"))
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/assets/", fs)))
jeevatkm
  • 4,571
  • 1
  • 23
  • 24
  • Tried those, they're less verbose alternatives, but their behaviour is exactly the same as the one I described: work in Postman, work really weirdly inside my application. – One-Winged_Eagle Aug 08 '17 at 04:24
  • Okay, could you create a working application with the issue you mentioned in your question and share a github link? It's very hard to figure out whats happening at your end. Typically on the server side every request gets served. It's not like first and subsequent fails. It might be some other issue you're facing. – jeevatkm Aug 08 '17 at 04:30
0

Just Add default CORS Middleware, i just test and it's work fine even i using difference domain. import this package from echo framework: "github.com/labstack/echo/middleware" and Add this default CORS config befor your route:

e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
}))
Rahmat Aligos
  • 1,164
  • 11
  • 13
-1

Welp, seems it was my application's fault all along! My Echo api seems fine... for now!

If someone has the same problem, perhaps this Vuejs with axios request in vuex store: can't make more than one request, why? will help.