简体   繁体   中英

Go gin - fetch data from local browser

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM