跨域请求问题总结

XMLHttpRequest.withCredentials

  • 是boolean类型,默认值是false
  • 他指示了是否使用资格证书来建立一个跨站点访问控制(cross-site Access-Control),同一个站点下该参数无效。
  • 其中资格证书有:cookie、authorization headers(头部受权)或TLS客户端证书等

实践

前提:跨域状况(同域下无效)vue

使用vue的代理proxy

vue项目中使用proxy代理服务,会转为同域,设置withCredentials=true,将不会形成影响,但发布到服务器出现跨域,将没法访问服务端接口,所以发布服务器不要采用代理。后端

设置withCredentials=true

一、Access-Control-Allow-Origin不能为*,不然将报错,以下:跨域

Failed to load http://localhost:3000/login: 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 'https://192.168.125.15:9527' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.服务器

解决办法:须要在后端增长Access-Control-Allow-Origin的须要跨域地址cookie

二、配合Access-Control-Allow-Credentials一块儿使用,不然将报错,以下:

Failed to load http://localhost:3000/login: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'https://192.168.125.15:9527' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. 解决办法:增长Access-Control-Allow-Credentialsapp

headers中增长自定义参数

响应首部Access-Control-Allow-Headers用于预检请求中列出将会在正式请求Access-Control-Request-Headers中容许的信息url

注意如下这些特定的首部是一直容许的:Accept, Accept-Language, Content-Language, Content-Type (但只在其值属于 MIME 类型 application/x-www-form-urlencoded, multipart/form-data 或 text/plain中的一种时)。这些被称做simple headers,你无需特地声明它们。3d

实践

  • 添加自定义头部变量token,Access-Control-Allow-Headers中并无添加容许的token将会报错

Failed to load http://localhost:3000/login: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.代理

  • 解决办法:后端增长Access-Control-Allow-Headers的token配置

相关文章
相关标签/搜索