gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:08:04 25 4
gpt4 key购买 nike

我有一个在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com