使用到的框架和工具介绍
前端框架:vue
请求工具:axios
后端框架:gin
遇到的问题介绍
tip:跨域中间键一定要在你路由之前全局使用。
1、请求没有修改过表头,这个应该很好解决,很多人已经提供了现成的方案
import (
"github.com/gin-gonic/gin"
)
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func main() {
r := gin.Default()
// 在这里调用中间键即可
r.Use(CORSMiddleware())
r.GET("/ping", func(c *gin.Context) {
//c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run("0.0.0.0:8080") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
2、请求有设置withCredentials或者在header里自定义字段的如Access-Control-Allow-Credentials 或者其他字段
先说withCredentials,如果你的请求设置了withCredentials=true,那么你大概会看到这样的报错
Access to XMLHttpRequest at 'http://xxxx/ping' from origin 'http://xxxx:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
意思就是如果你设置了credentials 那么后端Access-Control-Allow-Origin设置就不能用*,必须要写明允许访问的IP addr
解决方法:修改配置
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://xxx:8080")
// 对应上面CORSMiddleware方法的配置,将*改成指定ip
另外一种报错,自定义头部添加的key没有在配置允许内
Access to XMLHttpRequest at 'http://xxxx/ping' from origin 'http://xxxxx:8080' has been blocked by CORS policy:
Request header field access-control-allow-credentials is not allowed
by Access-Control-Allow-Headers in preflight response.
# https://stackoverflow.com/a/32501365/11757001
这个是因为配置时,Access-Control-Allow-Headers里缺少你自定义的key值access-control-allow-credentials
解决方法:修改配置
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With, Access-Control-Allow-Credentials")
// 对应上面CORSMiddleware方法的配置,在Access-Control-Allow-Headers里添加access-control-allow-credentials项,就可以正常访问了
// https://stackoverflow.com/a/32501365/11757001
这个前后端跨域访问的问题困扰了我大半天,希望我的经验可以帮助到你。