1. 基础知识

1.1 同源策略

同源:指在同一个域,就是两个页面具有相同协议域名端口

同源策略 (Sameoriginpolicy)是一种约定,它是浏览器最核心也是最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。

1.2 什么是跨域

当一个请求 url 的 协议、域名、端口 三者之间任意一个与当前页面的 url 不同时,即为跨域

当前页面 URL 被请求页面 URL 是否跨域 原因
http://www.test.com/ http://www.test.com/index.html 同源
http://www.test.com/ https://www.test.com/index.html 跨域 协议不同
(http != https)
http://www.test.com/ http://www.baidu.com 跨域 主域名不同
(test != baidu)
http://www.test.com/ http://blog.test.com/ 跨域 子域名不同
(www != blog)
http://www.test.com:8080/ http://www.test.com:7001/ 跨域 端口不同
(8080 != 7001)

1.3 非同源限制

  • 无法读取非同源网页的 Cookie、LocalStorage、IndexedDB
  • 无法接触非同源网页的 DOM
  • 无法向非同源地址发送 AJAX 请求

    1.4 跨域的解决办法

关于跨域的解决方法,大部分可以分为两种:

  1. nginx 反向代理解决跨域
  2. 服务端设置 Response Header(响应头部)的 Access-Control-Allow-Origin

对于后端开发者来说,第 2 种的操作性更为灵活,一般都用第2。


2. 简单请求

2.1 CORS标准

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

2.2 简单请求的结构

浏览器将 CORS 请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。 只要同时满足以下两大条件,就属于简单请求。
image.png
这是为了兼容表单(form),因为历史上表单一直可以发出跨域请求。AJAX 的跨域设计就是,只要表单可以发,AJAX 就可以直接发。
凡是不同时满足上面两个条件,就属于非简单请求。浏览器对这两种请求的处理,是不一样的

2.3 请求的基本流程

对于简单请求,浏览器直接发出CORS请求。具体来说,就是在头信息之中,增加一个 Origin 字段 。 下面是一个例子,浏览器发现这次跨源AJAX请求是简单请求,就自动在头信息之中,添加一个 Origin 字段。
image.png
上面的头信息中,Origin字段用来说明,本次请求来自哪个源(协议 + 域名 + 端口)。服务器根据这个值,决定是否同意这次请求。
如果Origin指定的源,不在许可范围内(不同源),服务器会返回一个正常的HTTP回应。浏览器发现,这个回应的头信息没有包含 Access-Control-Allow-Origin 字段(详见下文),就知道出错了,从而抛出一个错误,被XMLHttpRequest 的 onerror 回调函数捕获。注意,这种错误无法通过状态码识别,因为HTTP回应的状态码有可能是200。
如果Origin指定的域名在许可范围内(同源),服务器返回的响应,会多出几个头信息字段
image.png
上面的头信息之中,有三个与CORS请求相关的字段,都以 Access-Control- 开头。

(1)Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时 Origin 字段的值,要么是一个*,表示接受任意域名的请求。

(2)Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。

(3)Access-Control-Expose-Headers
该字段可选,用来指定可另外拿到的字段。CORS请求时,XMLHttpRequest对象的getResponseHeader( )方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。
如果想拿到其他字段,就必须在 Access-Control-Expose-Headers 里面指定。上面的例子指定,getResponseHeader(‘FooBar’)可以返回FooBar字段的值

【关于非简单请求以及更详细的内容,请参考阮一峰的博客:http://www.ruanyifeng.com/blog/2016/04/cors.html


3. 原生gin解决跨域

在 Gin 中提供了 middleware(中间件) 来做到在一个请求前后处理响应的逻辑。编写一个 Cors 中间件,在每次响应请求前均在请求上添加 Access-Control-Allow-Origin 头部

3.1 编写Cors中间件

该中间件是一个闭包,主要使用的方法为 c.Header,作用是用指定参数修改请求头
在 middleware 包下编写:

  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. func Cors() gin.HandlerFunc{
  7. return func(c *gin.Context) {
  8. method := c.Request.Method
  9. origin := c.Request.Header.Get("Origin")
  10. if origin != ""{
  11. // 接收客户端发送的origin (重要!)
  12. c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
  13. //服务器支持的所有跨域请求的方法
  14. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  15. //允许跨域设置可以返回其他子段,可以自定义字段
  16. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
  17. // 允许浏览器(客户端)可以解析的头部 (重要)
  18. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  19. //设置缓存时间
  20. c.Header("Access-Control-Max-Age", "172800")
  21. //允许客户端传递校验信息比如 cookie (重要)
  22. c.Header("Access-Control-Allow-Credentials", "true")
  23. }
  24. if method == "OPTIONS" {
  25. c.AbortWithStatus(http.StatusOK)
  26. }
  27. c.Next()
  28. }
  29. }

3.2 调用Cors

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "go_code/first_web/middleware"
  5. )
  6. func Test() gin.HandlerFunc{
  7. return func(c *gin.Context) {
  8. }
  9. }
  10. func main() {
  11. r := gin.New()
  12. r.Use(middleware.Cors())
  13. r.GET("xxx",Test())
  14. }

4. github.com/gin-contrib/cors 包

4.1 下载+导入

下载:

  1. go get github.com/gin-contrib/cors
  1. 导入
  1. import "github.com/gin-contrib/cors"

4.2 使用

  1. package main
  2. import (
  3. "time"
  4. "github.com/gin-contrib/cors"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. router := gin.Default()
  9. // CORS for https://foo.com and https://github.com origins, allowing:
  10. // - PUT and PATCH methods
  11. // - Origin header
  12. // - Credentials share
  13. // - Preflight requests cached for 12 hours
  14. router.Use(cors.New(cors.Config{
  15. AllowOrigins: []string{"https://foo.com"},
  16. AllowMethods: []string{"PUT", "PATCH"},
  17. AllowHeaders: []string{"Origin"},
  18. ExposeHeaders: []string{"Content-Length"},
  19. AllowCredentials: true,
  20. AllowOriginFunc: func(origin string) bool {
  21. return origin == "https://github.com"
  22. },
  23. MaxAge: 12 * time.Hour,
  24. }))
  25. router.Run()
  26. }
  27. Using DefaultConfig as start point
  28. func main() {
  29. router := gin.Default()
  30. // - No origin allowed by default
  31. // - GET,POST, PUT, HEAD methods
  32. // - Credentials share disabled
  33. // - Preflight requests cached for 12 hours
  34. config := cors.DefaultConfig()
  35. config.AllowOrigins = []string{"http://google.com"}
  36. // config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}
  37. router.Use(cors.New(config))
  38. router.Run()
  39. }
  1. 该包能够解决跨域主要取决于函数 **New**,该函数将设置请求头为指定的参数,函数原型为:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/2643809/1621433485720-4cda84d2-0586-4f98-b096-348a34ad08d4.png#clientId=u31fbcb7f-efab-4&from=paste&height=150&id=u669d9257&margin=%5Bobject%20Object%5D&name=image.png&originHeight=242&originWidth=1187&originalType=binary&size=49612&status=done&style=none&taskId=u02e843df-bf94-444e-acaf-9bb90a63a4d&width=737.5)<br />其入参为一个 **Config **结构体,结构体的字段包含允许跨域时请求头所需要的参数,原型为:
  1. / Config represents all available options for the middleware.
  2. type Config struct {
  3. AllowAllOrigins bool
  4. // AllowOrigins is a list of origins a cross-domain request can be executed from.
  5. // If the special "*" value is present in the list, all origins will be allowed.
  6. // Default value is []
  7. AllowOrigins []string
  8. // AllowOriginFunc is a custom function to validate the origin. It take the origin
  9. // as argument and returns true if allowed or false otherwise. If this option is
  10. // set, the content of AllowOrigins is ignored.
  11. AllowOriginFunc func(origin string) bool
  12. // AllowMethods is a list of methods the client is allowed to use with
  13. // cross-domain requests. Default value is simple methods (GET and POST)
  14. AllowMethods []string
  15. // AllowHeaders is list of non simple headers the client is allowed to use with
  16. // cross-domain requests.
  17. AllowHeaders []string
  18. // AllowCredentials indicates whether the request can include user credentials like
  19. // cookies, HTTP authentication or client side SSL certificates.
  20. AllowCredentials bool
  21. // ExposedHeaders indicates which headers are safe to expose to the API of a CORS
  22. // API specification
  23. ExposeHeaders []string
  24. // MaxAge indicates how long (in seconds) the results of a preflight request
  25. // can be cached
  26. MaxAge time.Duration
  27. // Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com
  28. AllowWildcard bool
  29. // Allows usage of popular browser extensions schemas
  30. AllowBrowserExtensions bool
  31. // Allows usage of WebSocket protocol
  32. AllowWebSockets bool
  33. // Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed
  34. AllowFiles bool
  35. }
  1. 当然,也可以在 middleware 里编写中间件 <br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/2643809/1621433880009-139ef608-6d0a-4620-a57f-1e635589ea3f.png#clientId=u31fbcb7f-efab-4&from=paste&height=324&id=u1f5bad64&margin=%5Bobject%20Object%5D&name=image.png&originHeight=630&originWidth=1443&originalType=binary&size=86753&status=done&style=none&taskId=u322fc1cb-977f-41b8-b279-7a7b90542a0&width=741)<br />然后在路由上挂载该中间件:
  1. func main() {
  2. r := gin.New()
  3. r.Use(middleware.Cors())
  4. r.GET("xxx",Test())
  5. }