Search code examples
dockerhttpaxiostraefik

axios cannot override host when making HTTP GET request to traefik reverse proxy


Context: I'm using traefik as my reverse proxy to send HTTP requests to my backend Golang server, which I've added some CORS handling. It works from Postman and when I'm cURLing the HTTP GET request

enter image description here

Problem: I'm getting this 404 error on the browser:

enter image description here

Axios call overriding Host

axios.create({
  baseURL: 'http://localhost',
})

axios.defaults.headers['Host'] = 'dev.docker.local'

got this error in the console

refused to set unsafe header "Host"

Axios call overriding default Host using X-Host-Override

axios.create({
  baseURL: 'http://localhost',
})

axios.defaults.headers['X-Host-Override'] = 'dev.docker.local'

Axios call setting default headers - seems like it's always using localhost as the Host

axios.create({
  baseURL: 'http://localhost',
  headers: {'Host': 'dev.docker.local'}
})

enter image description here

set CORS in route handlers

func About(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "*")

    aboutStruct := about{
        Name: "Hello world",
    }
    w.WriteHeader(http.StatusOK)
    j, _ := json.Marshal(aboutStrcut)
    w.Write(j)
}

Solution

  • finally found a way to solve this problem for the browser, needed to use dnsmasq to point docker.local to 127.0.0.1 and then set baseURL to dev.docker.local, no need to override Host