Skip to content

Cannot get basic version of in-browser Javascript application documentation working #158

@francoposa

Description

@francoposa

I cannot get any version of the documentation working with in-browser Javascript.

Everything works fine with curl/Postman. Browser javascript involves introducing a CORS library, but I do not think that is the problem, since after the CORS is introduced Postman workflow still works and the CORS library debug output does not show any issues.

Here is my code, stripped down as much as possible. I use Chi router because it is what I am familiar with, but that difference from the docs should not matter here.

go.mod:

go 1.17

require (
	github.com/go-chi/chi v1.5.4
	github.com/gorilla/csrf v1.7.1
	github.com/rs/cors v1.8.0
)

require (
	github.com/gorilla/securecookie v1.1.1 // indirect
	github.com/pkg/errors v0.9.1 // indirect
)

Go Code:

package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
	"github.com/gorilla/csrf"
	"github.com/rs/cors"
)

func main() {
	router := chi.NewRouter()

	// Suggested basic middleware stack from chi's docs
	router.Use(middleware.RequestID)
	router.Use(middleware.RealIP)
	router.Use(middleware.Logger)
	router.Use(middleware.Recoverer)

	corsMiddleware := cors.New(cors.Options{
		AllowOriginFunc: func(origin string) bool {return true},
		AllowCredentials: true,
		AllowedHeaders:   []string{"Content-Type", "X-CSRF-Token"},
		ExposedHeaders:   []string{"Content-Type", "X-CSRF-Token"},
		Debug:            true,
	}).Handler

	router.Use(corsMiddleware)

	CSRF := csrf.Protect(
		[]byte("place-your-32-byte-long-key-here"),
		csrf.RequestHeader("X-CSRF-Token"),
		csrf.Secure(false),
		csrf.TrustedOrigins([]string{"*localhost*"}),
	)

	// Routing to API handlers
	router.Route("/api", func(router chi.Router) {
		router.With(CSRF).Get("/", Get)
		router.With(CSRF).Post("/", Post)
	})

	srv := &http.Server{
		Handler:      router,
		Addr:         "localhost" + ":" + "8000",
		ReadTimeout:  time.Duration(15) * time.Second,
		WriteTimeout: time.Duration(10) * time.Second,
		IdleTimeout:  time.Duration(5) * time.Second,
	}

	fmt.Printf("starting http server on port %s...\n", "8000")
	log.Fatal(srv.ListenAndServe())

}

func Get(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("X-CSRF-Token", csrf.Token(r))
}

func Post(w http.ResponseWriter, r *http.Request) {}

Javascript:

axios.defaults.withCredentials = true

let get = async() => {
    let csrfToken = ""
    try {
        let resp = await axios.get("http://localhost:8000/api")
        console.log(resp)
        console.log(resp.headers)
        csrfToken = resp.headers["x-csrf-token"]
        console.log(csrfToken)
    } catch (err) {
        console.log(err)
    }

    const instance = axios.create({
        withCredentials: true,
        headers: {"X-CSRF-Token": csrfToken}
    })
    console.log(instance)
    return instance
}

let post = async(instance) => {
    try {
        let resp = await instance.post("http://localhost:8000/api", {})
        console.log(resp)
    } catch (err) {
        console.log(err)
    }
}

get()
    .then(axiosInstance => {
        post(axiosInstance)
    })

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions