vue在request时错误信息如下,做此记录:

Access to XMLHttpRequest at 'http://192.168.0.103:8080/user/userLogin' from origin 'http://localhost:8081' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Error: ERR_ACTION_ACCESS_UNDEFINED: Are you trying to access this.someMutation() or this.someGetter inside an @Action? 
That works only in dynamic modules. 
If not dynamic use this.context.commit("mutationName", payload) and this.context.getters["getterName"]

原因:得知当请求的凭证模式为'include'时'Access-Control-Allow-Origin' 头的值不能为通配符'*',这里面有一个关键字就是属性值withCredential,原因就是前后端对该项的设置没有统一。

同域安全策略CORS(Cross-Origin Resource Sharing) 
它要求请求的服务器在响应的报头(Response Header)添加 Access-Control-Allow-Origin标签,从而允许此标签所对应域访问此服务器的资源,调用此服务器的接口。

默认情况下请求不提供凭证,通过对withCredential的设置可以控制是否发送凭证。

如果发送的是带凭证的请求,但服务器响应中没有包含这个头部,那么该响应会被浏览器拦截,因此在需要传Cookie等时,服务端的Access-Control-Allow-Origin必须配置具体的域名。

如果服务器接收带凭证的请求会用Access-Control-Allow-Credentials:true的HTTP头部进行响应。

解决:前后端origins配置一致即可,凭证模式通过withCredentials 这个属性控制。个人后端使用的java springboot,先增加对跨域的设置@CrossOrigin(origins = "*", maxAge = 3600),并去掉前端(axios)设置项withCredentials: true。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐