什么是CORS
CORS(Cross-Origin Resource Sharing 跨源资源共享),当一个请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。
===前端
- 不需要携带cookies,authorization,则前端无需配置
- 需要携带cookies,authorization,前端的XMLHttpRequest.withCredentials属性需要设置为true。
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/', true); xhr.withCredentials = true; xhr.send(null);
使用axios的话,其已经进行封装,可以直接设置withCredentials
axios.defaults.withCredentials = true;
===服务端
- 添加允许跨域请求的域名(Access-Control-Allow-Origin)
需要配置:1.允许跨域请求的域;2.允许携带的头部;3.允许携带cookies,authorization
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';header("Access-Control-Allow-Headers: VERSION,token,If-Modified-Since,currentcity,currentprovince, Content-Type");header("Access-Control-Allow-Methods: HEAD,GET,POST,DELETE,PUT,OPTIONS"); $allow_origin = array( 'https://localhost:8090' // 本地调试跨域则需要本地请求地址 ); if (in_array($origin, $allow_origin)) { header('Access-Control-Allow-Origin:' . $origin); header('Access-Control-Allow-Credentials:true'); header('Access-Control-Allow-Headers: Origin,Accept, Authorization, X-Request-With,VERSION,token,currentcity,currentprovince, Content-Type'); }
不添加,则前端会报错,所请求的资源的允许跨域请求的域没有当前的域名。
使用http协议,Access-Control-Allow-Origin可以设置为*,Access-Control-Allow-Headers也可以不设置; 使用https协议,Access-Control-Allow-Origin必须设置为特定的域名,Access-Control-Allow-Headers也必须设置为特定字段。
- 禁止OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit; }
后端不禁止,会将options请求错误处理,发生找不到路由的情况。