Golang Gin:跨域资源共享中间件未生效
时间:2024-02-26
浏览:322
作者:佚名
Golang不知道大家是否熟悉?今天我将给大家介绍《Golang Gin:跨域资源共享中间件未生效》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
我收到了从我的前端应用程序到使用 gin 用 go 编写的后端应用程序的 post 请求。我收到一条错误消息:
“请求的资源上不存在‘access-control-allow-origin’标头”
这表明我在后端应用程序中实现 cors。所以我使用 "github.com/gin-contrib/cors":
web.go:
func newapp() *app {
db := setupdb()
router := gin.default()
router.use(cors.new(cors.config{
//alloworigins: []string{"http://localhost:3000", "http://127.0.0.1:3000"},
allowmethods: []string{"put", "post", "get", "options","delete"},
allowheaders: []string{"origin"},
allowallorigins: true,
//exposeheaders: []string{"content-length"},
allowcredentials: true,
maxage: 12 * time.hour,
}))
return &app{
db: db,
router: router,
}
}
在 main.go 中我有:
app := core.newapp()
//app.router.use(cors())
defer func() {
app.db.close()
log.printf("core: database stopping")
}()
app.router.use(func(c *gin.context) {
c.set("db", app.db)
})
app.router.get("/", func(ctx *gin.context) {
ctx.json(http.statusok, gin.h{"data": "welcome test"})
})
// initialize all api routes
routes.initializeroutes(app.router.group("/api/v1"))
如您所见,我仅在 allowmethods 中设置 put ,目的是测试 cors 是否实际工作。通过仅允许 put,我期望除了 put 之外不允许任何其他方法,但我错了。我已经从我的前端应用程序执行了 get 请求,并且它通过了(它返回数据),这让我认为 cors 实现没有被采纳。
在浏览时,我发现人们不使用包 "github.com/gin-contrib/cors" 而是创建自己的中间件:
func cors() gin.handlerfunc {
return func(c *gin.context) {
fmt.println(c.request.header)
c.writer.header().set("access-control-allow-origin", "*")
c.writer.header().set("access-control-allow-credentials", "true")
c.writer.header().set("access-control-allow-headers", "content-type, content-length, accept-encoding, x-csrf-token, authorization, accept, origin, cache-control, x-requested-with")
//c.writer.header().set("access-control-allow-methods", "post, options, get, put, delete")
c.writer.header().set("access-control-allow-methods", "put, delete")
if c.request.method == "options" {
c.abortwithstatus(204)
return
}
c.next()
}
}
然后:
func NewApp() *App {
db := SetUpDB()
router := gin.Default()
router.Use(CORS())
return &App{
Db: db,
Router: router,
}
}
我也尝试过这个,但没有运气。同样的结果也会回来。
此外,当我执行 get 并在后端打印该方法 (c.request.method) 时,结果是 get。但是当我执行 post 并打印该方法时,我得到 options
我错过了什么?为什么 router 没有使用提供的中间件?
正确答案
这个问题有两个部分:
第一个是上面 heiko 指出的:get 是一个简单的请求,因此此类请求总是会返回结果。
现在,在测试了我的
post后,我仍然遇到错误。我一遍又一遍地检查 cors 配置,到处更改内容,只是为了发现类别的路由定义如下:
categoryrouter.post("/", controllers.createnewcategory)
categoryrouter.get("/", controllers.listallcategories)
正如您所看到的,有一个尾随的 / 导致我的请求被重定向并返回错误,因为用于请求的 url 是 http://127.0.0.1:8080/api/v1/类别。我将路线更新为:
categoryRouter.POST("", controllers.CreateNewCategory)
categoryRouter.GET("", controllers.ListAllCategories)
现在它正在按预期工作。
今天关于《Golang Gin:跨域资源共享中间件未生效》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
