Home > OS >  Go gin - fetch data from local browser
Go gin - fetch data from local browser

Time:03-19

I have a simple server written with Go Gin:

package main

import (
    "net/http"

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    router.Use(cors.Default())
    router.GET("/", func(context *gin.Context) {
        context.JSON(http.StatusOK, gin.H{"hello": "world"})
    })

    router.Run(":8080")
}

If I do a fetch from Firefox console (97.0.2 (64-bit) on Ubuntu):

fetch('http://localhost:8080/')
  .then(response => response.json())
  .then(data => console.log(data));

I get the following error:

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:8080/ 
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

While, if I do the same HTTP GET request from a terminal with curl, I get the correct result:

curl -X GET http://localhost:8080/

{"hello":"world"}

Is it possible to test the Go gin server using the browser?

CodePudding user response:

If you try to do ajax request from different location then the request request location then the request will be blocked by Content Security Policy (CSP) which help to detect and mitigate certain types of attacks. You can read more about CSP here.

For fetch to work you have to go to the same location and make fetch request from that location in your case it is http://localhost:8080/.

Note: Since you have defined the root route to return json when you open the location in browser which may raise a GET request and the response json will be returned in browser.

  • Related