- 新增中间件cors
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", "*") //可选 如果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数量、名称与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.
posted on 2019-12-26 11:17
一凡 阅读(318)
评论(0) 编辑 收藏 所属分类:
Golang