42

Go | Gin 解决跨域问题跨域配置

 3 years ago
source link: https://studygolang.com/articles/30669
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

<h1> Go | Gin 解决跨域问题跨域配置 </h1>

前言

在前后端分离的项目中,经常会遇到跨域问题,遇到问题该如何解决呢?!

一、关于跨域解决方案

关于跨域的解决方法,大部分可以分为 2 种

Access-Control-Allow-Origin

对于后端开发来说,第 2 种的操作性更新灵活,这里也讲一下 Gin 是如何做到的

二、使用步骤

在 Gin 中提供了 middleware (中间件) 来做到在一个请求前后处理响应的逻辑,这里我们使用中间来做到在每次请求是添加上 Access-Control-Allow-Origin 头部

1. 编写一个中间件

可以 middlewares 包下创建

package middlewares

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

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        method := c.Request.Method
        if origin != "" {
        // 可将将* 替换为指定的域名
            c.Header("Access-Control-Allow-Origin", "*") 
            c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
            c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
            c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
            c.Header("Access-Control-Allow-Credentials", "true")
        }

        if method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
        }

        c.Next()
    }
}

2. 使用

r := gin.Default()

r.Use(middlewares.Cors())

3. 注意事项

需要将 r.Use(middlewares.Cors()) 在使用路由前进行设置,否则会导致不生效

反例

r := gin.Default()

pingGroup := r.Group("ping")
{
    pingGroup.GET("/", Ping)
}

r.Use(middlewares.Cors())

这样会导致跨域配置不生效

a6rUz2.jpg!mobile

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK