douxuanma4357
2018-12-29 00:19
浏览 327
已采纳

在localhost:8080上运行的服务器从在9090上运行的前端获取CORS

I have a API-server (gin-gonic) running on localhost:8080. All the typical CORS-Header are set for debugging: When I try to test the API with a simple Frontend (swagger-ui) i get a CORS-error. (swagger is running on localhost:9090)

It works when everything is running on the same domain.

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")

why is this not working. Should the 3 lines not keep all CORS problems away?

Im super curious for actual explanations rather than a plain solution. All resources regarding this (or a good one about CORS) are welcome.

It works fine in Postman or CURL

Errormessage in browser: CORS Error Message

图片转代码服务由CSDN问答提供 功能建议

我有一个在本地主机上运行的API服务器(gin-gonic):8080。 所有典型的CORS-Header 设置用于调试: 当我尝试使用简单的前端(swagger-ui)测试API时,出现CORS错误。 (swagger在本地主机上运行: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“)
   
 
 

为什么这不起作用。 这三行代码是否不能解决所有CORS问题?

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

在Postman或CURL中工作正常

浏览器中的错误消息:

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulan8846 2018-12-30 08:15
    已采纳

    When you catch OPTION as Preflight request your server should return success. I cannot find return in your provided code.

    Also you can try to use 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")
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题