在Golang的道路上,慢慢前进Gin框架跨域问题的说明和方法。

代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

Package main

Import(

github.com/gin-gonic/gin’

“AwesomeProject/app/app_routers”

“字串”

“Fmt”

“Net/http”

)。

/*路由初始化*/

Var(

Engine=gin。Default()

)。

Func main() {

//允许跨域请求使用全局中间件

Engine。Use(Cors())

//router。Use(cors)。Default())

//设置参数路由组允许路由组使用路由

App_routers。路由器(engine)

//启动路由设置端口

Cors()

Engine。运行run(' 336011000 ')//启动端口

}

//

//跨域

Func Cors() gin。HandlerFunc {

Return func(c *gin)。Context) {

Method :=c.Request.Method //请求方法

origin :=c . request . header . get(' origin ')//请求头

Var headerKeys []string //请求标头Keys声明

For k,_ :=range c.request.header {

标头键=append(标头键,K)

}

header str 3360=strings . join(header键,',')

If headerStr!='' {

header str=fmt . sprintf(' access-control-allow-origin,access-control-allow-headers,)

} else {

header str=' access-control-allow-origin,access-control-allow-headers '

}

If origin!='' {

C.writer.header()。set(' access-control-allow-origin ',' * ')

C.Header(' access-control-allow-origin ',' *')//这是允许访问所有域

C.Header(' access-control-allow-methods ',' post,get,options,put,delete,update ')

//header的类型

C.Header(‘access-control-allow-headers’、authorization、content-length、x-csrf-Conners)

//允许跨域设置返回不同的子段

C.Header(‘access-control-expose-headers’,‘Content-length,access-control-allow-)cc

C.header ('access-control-max-age ',' 172800')//缓存请求信息单位秒

C . header(' access-control-allow-credentials ',' false')//跨域请求是否需要cookie信息默认设置为true

C.set(“内容类型”,“应用程序/JSON”)//设置返回格式JSON

}

//推出所有选项方法

If method==' OPTIONS ' {

C.JSON (http.status ok,‘options request!’))。

}

//处理请求

C.Next() //处理请求

}

}

添加:解决跨域问题的Jin框架中间件

代码如下:

Func Cors(c *gin)。Context) {

C.Header(' access-control-allow-origin ',' * ')

C.Header(‘access-control-allow-headers’、‘content-type、access token、x-csrf-toker’)

C.Header(‘access-control-allow-methods’,post,get,options,put,patch,delete’)

C.Header(‘access-control-expose-headers’、‘content-length、access-control-allow-))

C . header(' access-control-allow-credentials ',' true ')

//这里是解决vue的那个坑

Method :=c.Request.Method

//释放所有OPTIONS方法。因为有些模板需要请求两次

If method==' OPTIONS ' {

C.abortwithstatus(http . status nocontent)

}

//处理请求

C.Next()

}