修改跨域处理

This commit is contained in:
junleea 2024-09-27 20:52:14 +08:00
parent 76cb556042
commit 56cab15a73
1 changed files with 27 additions and 32 deletions

View File

@ -1,32 +1,27 @@
package handler package handler
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
//"net/http" "net/http"
) //"net/http"
)
//跨域访问cross origin resource share
func CrosHandler() gin.HandlerFunc { // 跨域访问cross origin resource share
return func(context *gin.Context) { func CrosHandler() gin.HandlerFunc {
//method := context.Request.Method return func(c *gin.Context) {
context.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // 或者设置为具体的源
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域 c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token, Session, X-Requested-With, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language, DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma, Token, OpenId, OpenToken")
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken") c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, FooBar")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") c.Writer.Header().Set("Access-Control-Max-Age", "172800")
context.Header("Access-Control-Max-Age", "172800") // 如果需要发送cookies请确保设置了具体的源而不是*并将Allow-Credentials设置为true
context.Header("Access-Control-Allow-Credentials", "false") // c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
context.Set("content-type", "application/json") //设置返回格式是json
if c.Request.Method == "OPTIONS" {
// if method == "OPTIONS" { c.AbortWithStatus(http.StatusOK)
// context.JSON(http.StatusOK, gin.H{ return
// "code":1, }
// "message":"error",
// "data":"request error", c.Next()
// }) }
// } }
//处理请求
context.Next()
}
}