1. 程式人生 > >碰到一個ant design跨域問題

碰到一個ant design跨域問題

antd-admin跨域

今天碰到了一個跨域問題,折騰了半天,終於解決了。

項目背景:采用前端模版框架ant design的腳手架antd-admin做開發時,在本地做開發時,發現即使設置成post方法,也會通過get發送請求。逐步查詢發現采用的都是JSONP格式請求。而JSONP的缺點則是:它只支持GET請求而不支持POST等其它類型的HTTP請求;它只支持跨域HTTP請求這種情況,不能解決不同域的兩個頁面之間如何進行JavaScript調用的問題。

於是查看util下面的request.js文件,發現代碼如下:

  export default function request (options) {
    if (options.url && options.url.indexOf(‘//‘) > -1) {
      const origin = `${options.url.split(‘//‘)[0]}//${options.url.split(‘//‘)[1].split(‘/‘)[0]}`
      if (window.location.origin !== origin) {
        if (CORS && CORS.indexOf(origin) > -1) {
          options.fetchType = ‘CORS‘
        } else if (YQL && YQL.indexOf(origin) > -1) {
          options.fetchType = ‘YQL‘
        } else {
          options.fetchType = ‘JSONP‘
        }
      }
    }

經測試發現本地都走的JSONP的類型, 在看下面的代碼。

  if (fetchType === ‘JSONP‘) {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: ‘OK‘, status: 200, data: result })
      })
    })
  } 

將所有的參數,作為url的參數的後面追加。於是問了一下前端的大神,結合現實情況,總結修改方案如下:

  • 前端框架采用json格式請求,對於post的請求先發送method=OPTIONS的請求, 如果返回的是204狀態,則放過,然後在發送實際請求。
  • 後端api接口曾需要放過method=OPTIONS的請求,並且返回204的狀態。

具體解決方案:
(1) 註銷上面jsonp直接返回的代碼,所有請求都采用json格式。放過204的狀態。

    return fetch(options).then((response) => {
        if (response.status === 204) {
            return response.text()
        }
        ... ...

(2) server端放過method=OPTIONS的請求, 返回204。

if ($_SERVER[‘REQUEST_METHOD‘] == ‘OPTIONS‘) {
    header(‘Access-Control-Allow-Origin: *‘);
    header(‘Content-Type:application/json; charset=utf-8‘);
    header(‘Access-Control-Allow-Methods: "GET, POST, OPTIONS, PUT, DELETE"‘);
    header(‘Access-Control-Allow-Headers: content-type‘);
    header(‘Access-Control-Max-Age: 1000‘);
    http_response_code(‘204‘);
    exit;
 }

(3) 對於json格式的請求,也要返回相應的頭部。

case ‘JSON‘:
    // 返回JSON數據格式到客戶端 包含狀態信息
    header(‘Access-Control-Allow-Origin: *‘);
    header(‘Content-Type:application/json; charset=utf-8‘);
    header(‘Access-Control-Allow-Methods: "GET, POST, OPTIONS, PUT, DELETE"‘);
    header(‘Access-Control-Max-Age: 1000‘);
    exit(json_encode($data));

因為內部系統初期開發,暫時沒有細節優化。僅實現功能,解決問題為主。

碰到一個ant design跨域問題