api接口開發跨域注意事項和設置

由於跨域請求會先發送一個OPTIONS請求,因此須要判斷下OPTIONS請求的就直接返回json

if(strtoupper($_SERVER['REQUEST_METHOD'])== 'OPTIONS'){
      header("Access-Control-Allow-Origin:*");
      header("Access-Control-Allow-Headers:content-type");
      header("Access-Control-Request-Method:GET,POST");
      exit;
}

在返回json數據的時候須要在頭部加上跨域

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST');
header('Access-Control-Allow-Headers: Destination, Content-Type, User-Agent, X-Requested-With, If-Modified-Since');
header('Access-Control-Allow-Credentials: true');
相關文章
相關標籤/搜索