我有一个在 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 中工作正常
最佳答案
当您捕获 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/