问题描述:

前端无法向后端传递cookie。在用户登录时,我首先记录了登录的信息,并通过cookie存储到客户端,客户端接收到了cookie,但是在下次请求中并没有携带cookie信息

问题分析:

在前后端不在同一个域的情况下,浏览器默认无法主动跨域向后端发送cookie,服务器也不会主动的接收

解决方法:

  1. 在前端设置withCredentials:true
  2. 服务端设置Access-Control-Allow-Credentials: true

go跨域设置:

package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

//解决跨域访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "api.ordertracking.com") // 可将将 * 替换为指定的域名
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}