react揚帆起航以前後端數據交互

本文信息

  • 本文建立於2018/03/07
  • 2018/03/20 新增 -- 攔截器

前述

先後端交互是開發現代應用必不可少的內容,不一樣於angular內置HttpClientModule,react默認並未提供用於http請求的功能。咱們直接使用fetch,但一些老舊的瀏覽器支持度不太好。本文中,咱們推薦使用基於Promise的庫 -- axiosreact

axios的基本用法很是簡單,跟jqueryajax相似。jquery

設置baseUrl

若是restful api至於一個單獨域名之下,且支持跨域。咱們能夠對axios進行自定義配置設置baseUrl並封裝。ios

// client.ts

import axios from 'axios';

axios.defaults.baseURL = 'http://api.example.com';

export default axios;

使用時直接調用client.ts便可:git

// 使用示例
import client from 'client.ts';
...
  client.get('/api/v0/test')
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });
...

攔截器

// client.ts
import axios from 'axios';

// 請求頭攜帶token
axios.interceptors.request.use(
  (config) => {
    const storageCredential = localStorage.getItem('credentials');
    const credentials = storageCredential ? JSON.parse(storageCredential) : null;
    if (credentials && credentials.access_token) {
      config.headers = { ...config.headers, Authorization: 'Bearer ' + credentials.access_token };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 處理response
axios.interceptors.response.use(
  (response) => {
    // success handle
    return response;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // 401 handle
    }
    return Promise.reject(error);
  });

  export default axios;

開發環境下proxy設置

通常狀況下,react在開發環境下會啓動一個dev server,假設咱們此時又啓動了一個api server用於提供後端數據,那麼就會涉及一個跨域的問題。爲了解決跨域問題,咱們就須要進行代理配置。具體實現方式爲,在package.json裏添加(以api server端口號3000爲例):github

/* package.json */
"proxy": {
  "/api": {
    "target": "http://localhost:3000",
    "secure": "false"
  }
}

至此,先後端數據交互的內容完畢。ajax


react揚帆啓航專欄分享的時我我的學習與實踐react過程當中的一些歷程,但願藉此專欄與你們共同探討react相關的技術,以求進步。json

相關文章
相關標籤/搜索