go - 在本地主机 :8080 getting CORS from frontend running on 9090 上运行的服务器

标签 go go-gin

我有一个在 localhost:8080 上运行的 API 服务器 (gin-gonic)。 所有典型的 CORS-Header 都设置为调试: 当我尝试使用简单的前端 (swagger-ui) 测试 API 时,出现了 CORS 错误。 (swagger 在 localhost:9090 上运行)

当一切都在同一个域上运行时,它会起作用。

c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

为什么这不起作用。难道这 3 行代码不能解决所有 CORS 问题吗?

我非常想知道实际的解释,而不是简单的解决方案。欢迎所有与此相关的资源(或有关 CORS 的好资源)。

它在 Postman 或 CURL 中工作正常

浏览器报错: CORS Error Message

最佳答案

当您捕获 OPTION 作为预检请求时 您的服务器应该返回成功。我在您提供的代码中找不到返回值。

您也可以尝试使用 https://github.com/rs/cors

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    cors "github.com/rs/cors/wrapper/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")
}

关于go - 在本地主机 :8080 getting CORS from frontend running on 9090 上运行的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53965657/

相关文章:

Go:为 code.google.com/p/go.text/transform 制作转换器

unit-testing - 在 Golang 中制作模拟 gin.Context

Golang gin gonic web 框架代理路由到另一个后端

go - 如何同时使用 LoadHTMLGlob 和 LoadHTMLFiles

layout - 是否需要 go 才能使用包

go - Bazel go_binary c-共享链接模式 : Where is the header?

json - 如何在 golang 中使用 Unmarshal 从 json 文档中获取结构中的 json 字符串

go - Go 中的 Data Race 和 Condition 有什么区别?

go - Gin 上传文件时始终返回204

json - 使用 PUT 在一个请求中更新多个 JSON 数据