Golang 框架 Gin 踩坑笔记-跨域问题

前后端分离,后端使用Gin,POST的接口老是OPTIONS返回404,用postman测试接口正常,最后发现,跨域中间键一定要在你路由组(group)之前全局使用,最好在gin.Default()之后就使用,否则中间件拿不到OPTIONS的请求,导致会404

中间件代码:

/**
 * @Author: Ne-21
 * @Description: 跨域
 * @File:  CORS
 * @Version: 1.0.0
 * @Date: 2022/1/27 12:05
 */

package middleware

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        method := c.Request.Method
        c.Header("Access-Control-Allow-Origin", "*")                                                     // 可将将 * 替换为指定的域名
        c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization") //你想放行的header也可以在后面自行添加
        // c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
        c.Header("Access-Control-Allow-Credentials", "true")

        // 放行所有OPTIONS方法
        if method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
        }
        // 处理请求
        c.Next()
    }
}

我使用的位置

/**
 * @Author: Ne-21
 * @Description:
 * @File:  main.go
 * @Version: 1.0.0
 * @Date: 2022/1/26 13:18
 */

package main

import (
    "github.com/Olixn/Bing-Wallpaper-Server/config"
    "github.com/Olixn/Bing-Wallpaper-Server/controller"
    "github.com/Olixn/Bing-Wallpaper-Server/middleware"
    "github.com/Olixn/Bing-Wallpaper-Server/route"
    "github.com/gin-gonic/gin"
)

func init() {
    config.InitConfig()
    config.InitMySQL()
    controller.InitBingCrawler()
}

func main() {
    r := gin.Default()

    r.Use(middleware.Cors())
    route.RegisterRoute(r)
    r.Run(":9090")
}

版权声明:
作者:Ne-21
链接:https://blog.gocos.cn/archives/203.html
来源:云淡风轻
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Golang 框架 Gin 踩坑笔记-跨域问题
前后端分离,后端使用Gin,POST的接口老是OPTIONS返回404,用postman测试接口正常,最后发现,跨域中间键一定要在你路由组(group)之前全局使用,最好在gin.D……
<<上一篇
下一篇>>