新增中間件corsfunc Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*") //必選
c.Header("Access-Control-Allow-Headers", "*") //可選 如果request有header, 必選
//c.Header("Access-Control-Allow-Credentials", "true") //可選
//c.Header("Access-Control-Allow-Methods", "*") //可選
//c.Header("Access-Control-Expose-Headers", "*") //可選
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusOK)
}
// 處理請求
c.Next()
}
}
在router里增加cors,必須在group之前,全局設置
r.Use(gin.Logger(), gin.Recovery(), cors.Cors())
測試代碼,header設置不能多于cors設置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link type="test/css" href="css/style.css" rel="stylesheet">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#cors").click(
function(){
$.ajax({
headers:{
"Content-Type":"application/json;charset=UTF-8",
"Access":"adsad",
"Access-Token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJwYXNzd29yZCI6InRlc3QxMjM0NTYiLCJleHAiOjE1NzczMzY3MTIsImlzcyI6Imdpbi1ibG9nIn0.wMlQXqZO2V0LR-FIgDh45LWI0OYMYi6an_NvRmF0Nug"
},
url:"http://127.0.0.1:8000/api/v1/articles",
success:function(data){
console.log("start");
console.log(data);
}
})
});
});
</script>
<body>
<input type="button" id="cors" value="core跨域測試">
</body>
</html>
請求的headers數(shù)量、名稱與cors里的設置需要嚴格對應,不然報錯如下
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1/articles' from origin 'http://localhost:9999' has been blocked by CORS policy: Request header field access is not allowed by Access-Control-Allow-Headers in preflight response.

]]>