Axio使用withCredentials后跨域请求出现错误

在前后端分离的项目里,因为前端和后端不在一个域上,所以为了在使用跨域请求带上cookie,要把withCredentials设置为true

1
axios.defaults.withCredentials = true

但是设置完之后,访问又出现了如下的问题

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'. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

解决方案

  • 设置Access-Control-Allow-Origin字段为指定域名,不能为*
  • 设置Access-Control-Allow-Credentials设置为true
1
2
3
4
corsconfig := cors.DefaultConfig()
corsconfig.AllowOrigins = []string{"http://localhost:3000"}
corsconfig.AllowCredentials = true
engine.Use(cors.New(corsconfig))

reference: https://www.cnblogs.com/cnxkey/articles/14259716.html