前后端分离开发,前端添加新的请求头 "Access-Token"
,发送请求时报错:
Access to XMLHttpRequest at 'http://localhost:8080/api' from origin 'http://localhost:5432' has been blocked by CORS policy: Request header field access-token is not allowed by Access-Control-Allow-Headers in preflight response.
在cors的配置项AllowHeaders
上添加需要的请求头 "Access-Token"
AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "Access-Token"},
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
engine := gin.Default()
allowCors(engine)
// 允许跨域访问,在前后端分开部署时必须启用
func allowCors(engine *gin.Engine) {
engine.Use(cors.New(cors.Config{
//准许跨域请求网站,多个使用,分开,限制使用*
AllowOrigins: []string{"*"},
//准许使用的请求方式
AllowMethods: []string{"PUT", "PATCH", "POST", "GET", "DELETE"},
//准许使用的请求表头
AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "Access-Token"},
//显示的请求表头
ExposeHeaders: []string{"Content-Type"},
//凭证共享,确定共享
AllowCredentials: true,
//容许跨域的原点网站,可以直接return true就万事大吉了
AllowOriginFunc: func(origin string) bool {
return true
},
//超时时间设定
MaxAge: 24 * time.Hour,
}))
}