今天敲代码的时候遇到了这么一个问题,开始以为是跨域,后端说他们写的demo都没有问题。
后面才发现原来是因为withCredentials导致的。通过搜索发现,当withCredentials = true时:
- 接口响应头里面的
Access-Control-Allow-Origin不能是*,要设置为你的前端项目源地址,例如http://localhost:8000/; Access-Control-Allow-Credentials要设置为true。
如果后端接口的响应头里面必须是Access-Control-Allow-Origin = '*',那么前端这边应该设置withCredentials = false。
withCredentials:指示了是否该使用类似 cookie、Authorization 标头或者 TLS 客户端证书等凭据进行跨站点访问控制(Access-Control)请求。设置 withCredentials 对同源请求是无效的。