## 1.H5游戏前端开发的跨域问题 在h5游戏前端开发的过程中经常出现跨域问题,如下方的错误 ```shell Access to XMLHttpRequest at 'http://www.xxx.com/api/index' from origin 'http://172.17.1.3:3000' has been blocked by CORS policy: 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. ``` 先前我也一直有接触相关的内容,但是都是皮毛,并没有太多的时间去认真研究到底是怎么回事,只知道nginx改成 > Access-Control-Allow-Origin: * 能用就行,但是这并不是严谨的科学态度,我还是想去深入了解,毕竟在日常开发工作中都要用到的,一知半解很容易出问题,如同这个问题,请参看 [withCredentials属性](#3.withCredentials属性) ## 2.什么是跨域 ## 3.withCredentials属性 ```shell let xhr = new Laya.HttpRequest(); xhr.http.withCredentials = false; xhr.http.timeout = 5000; ``` 跨域请求默认不发送cookie信息,如果需要发送cookie,则需要服务器和客户端同时设置 服务器设置 > Access-Control-Allow-Credentials: true 客户端设置 > xhr.http.withCredentials = true 1. 如果服务器设置了,客户端没设置,客户端不会发送cookie到服务器 2. 如果客户端设置了,服务器没设置,则会提示跨域错误,如文章开头看到到跨域问题,就是因为服务器没有设置,而客户端设置了withCredentials引起到。 3. 如果省略withCredentials设置,有的浏览器默认设置是开启状态,因此最好直接设置为false VSCode使用常用姿势 游戏版本发布管理
No Leanote account? Sign up now.