React + Laravel Debugbar

yanthink發表於2018-09-14

一、Debugbar 安裝與配置

1、使用 Composer 安裝該擴充套件包:

composer require barryvdh/laravel-debugbar --dev

2、接下來執行以下命令生成此擴充套件包的配置檔案 config/debugbar.php :

php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"

3、開啟 config/debugbar.php 檔案,修改如下配置:

return [
    ...
    'capture_ajax' => false,
    'inject' => false,
    ...
],

4、開啟 app/Providers/RouteServiceProvider.php 檔案,在 boot 方法裡新增一條渲染路由

public function boot()
{
    if ($this->app->environment('local')) {
        Route::group(['prefix' => config('debugbar.route_prefix')], function () {
            Route::get('render', function () {
                $debugBar = debugbar();
                $renderer = $debugBar->getJavascriptRenderer();
                $renderer->setOpenHandlerUrl('/' . config('debugbar.route_prefix') . '/open');
                $script = $renderer->render();
                preg_match('/(?:<script[^>]*>)(.*)<\/script>/isU', $script, $matches);

                $js = $matches[1];

                $jsRetryFn = "function retry(times, fn, sleep) {
                                 if (!times) times = 1;
                                 if (!sleep) sleep = 50;
                                 --times;
                                 try {
                                     return fn();
                                 } catch (e) {
                                     if (!times) throw e;
                                     if (sleep) {
                                         setTimeout(function() {
                                             retry(times, fn, sleep);
                                         }, sleep);
                                     }
                                 }
                              }\n";

                // sleep(1);
                echo "${jsRetryFn}\nretry(50, function() {\n${js}\nwindow.phpdebugbar = phpdebugbar\n}, 200);";
                exit;
            });
        });
    }

    parent::boot();
}

5、開啟 app/Providers/AppServiceProvider.php 檔案,在 boot 方法裡新增如下程式碼:

public function boot()
{
    if (app()->environment('local') && request()->isJson()) {
        $debugbar = debugbar();
        $debugbar->sendDataInHeaders(true);
    }
}

二、react 配置

1、安裝 react-helmet 擴充套件包

npm i -S react-helmet

2、載入 js 和 css 檔案,並且渲染debugbar

import { Helmet } from 'react-helmet';

const cssMap = [];
const jsMap = [];
if (process.env.NODE_ENV !== 'production') {
  cssMap.unshift('/_debugbar/assets/stylesheets');
  jsMap.unshift('/_debugbar/assets/javascript', '/_debugbar/render');
}

ReactDOM.render(
    <Helmet>
        {cssMap && cssMap.map((_, k) => <link rel="stylesheet" href={_} key={String(k)} />)}
        {jsMap && jsMap.map((_, k) => <script type="text/javascript" src={_} key={String(k)} />)}
    </Helmet>
)

3、api 請求自動重新整理debugbar渲染

import fetch from 'dva/fetch';
import { notification } from 'antd';
import { routerRedux } from 'dva/router';
import cookie from 'cookie';
import store from '../index';

const codeMessage = {
  200: '伺服器成功返回請求的資料。',
  201: '新建或修改資料成功。',
  202: '一個請求已經進入後臺排隊(非同步任務)。',
  204: '刪除資料成功。',
  400: '發出的請求有錯誤,伺服器沒有進行新建或修改資料的操作。',
  401: '使用者沒有許可權(令牌、使用者名稱、密碼錯誤)。',
  403: '使用者得到授權,但是訪問是被禁止的。',
  404: '發出的請求針對的是不存在的記錄,伺服器沒有進行操作。',
  406: '請求的格式不可得。',
  410: '請求的資源被永久刪除,且不會再得到的。',
  422: '當建立一個物件時,發生一個驗證錯誤。',
  500: '伺服器發生錯誤,請檢查伺服器。',
  502: '閘道器錯誤。',
  503: '服務不可用,伺服器暫時過載或維護。',
  504: '閘道器超時。',
};

async function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const { dispatch } = store;
  const { status } = response;

  if (status === 401) {
    dispatch({ type: 'login/logout' });
  } else if (status === 403) {
    dispatch(routerRedux.push('/exception/403'));
  } else if (status === 404) {
    dispatch(routerRedux.push('/exception/404'));
  } else if (status >= 500 && status <= 504) {
    dispatch(routerRedux.push('/exception/500'));
  } else if (status >= 404 && status < 422) {
    //
  }

  const errorText = codeMessage[response.status] || response.statusText;
  const { message: msg } = await response.json();

  notification.error({
    message: `請求錯誤 ${response.status}: ${response.url}`,
    description: msg || errorText,
  });

  const error = new Error(msg || errorText);
  error.name = response.status;
  error.response = response;
  throw error;
}

export default async function request(url, options) {
  const defaultOptions = {
    method: 'GET',
    credentials: 'include',
    headers: {
      Accept: 'application/x.einsition.v1+json',
      'Content-Type': 'application/json; charset=utf-8',
      'X-XSRF-TOKEN': cookie.parse(document.cookie)['XSRF-TOKEN'],
    },
  };
  const newOptions = { ...defaultOptions, ...options };

  if (['POST', 'PUT', 'PATCH'].includes(newOptions.method.toUpperCase())) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.body = JSON.stringify(newOptions.body);
    }
  }

  const response = await fetch(url, newOptions);

  /* eslint-disable */
  if (typeof phpdebugbar !== undefined) {
    try {
      const {
        ajaxHandler: { headerName },
      } = phpdebugbar;
      const debugBarData = response.headers.get(headerName);
      const debugBarId = response.headers.get(`${headerName}-id`);
      if (debugBarData) {
        const { id, data } = JSON.parse(decodeURIComponent(debugBarData));
        phpdebugbar.addDataSet(data, id);
      } else if (debugBarId && phpdebugbar.openHandler) {
        phpdebugbar.loadDataSet(debugBarId, '(ajax)');
      }
    } catch (e) {}
  }
  /* eslint-enable */

  await checkStatus(response);
  return response.json();
}

file

相關文章