天天看點

react學習系列3 使用koa-router模拟背景接口

當用create-react-app建立好項目,啟動後會自動打開 localhost:3000。

我們希望當通路 localhost:3000/api/todo 會向背景發起一個請求,拿到我們想要的 json 資料。并渲染到前台。

這樣的話需要先建立一個背景伺服器。我們使用NodeJS的 express 或 koa 伺服器架構。下面以 koa 為例。

實作方法如下:

  1. 安裝koa和koa-router。注意我的目前版本是最新的 koa2.3.0 和 koa-router7.2.1

    yarn add koa koa-router

  2. 項目根目錄建立一個mock目錄,并建立一個server.js

    内容如下:

var Koa = require('koa');
var Router = require('koa-router');

var app = new Koa();
var router = new Router();

router.get('/', function (ctx, next) {
  console.log('say');
  ctx.body = 'hello koa !'
});

// 加字首
router.prefix('/api');

// 模拟json資料
var todo = require('./todo.js')
router.get('/todos', function (ctx, next) {
  console.log('--todo--')
  ctx.body = todo
});

// 開始服務并生成路由
app.use(router.routes())
   .use(router.allowedMethods());
app.listen(4000);
           

todo.js

module.exports = [
    {
        title: 'title1',
    },
    {
        title: 'title2',
    }
]
           
  1. package.json 添加代理資訊

    "proxy": "http://localhost:4000",

    這樣當我們在create-react-app的代碼裡調用

    fetch('api/todos')

    會被代理執行

    http://localhost:4000/api/todos

    并且在 script 節點下添加

    "mock": "node ./mock/server.js"

    這樣執行

    yarn mock

    就啟動了這個背景服務
  2. 在 react 中比如入口的 index.js 中添加測試代碼。

    我們使用

    fetch ,發起用戶端請求。
fetch('/api/todos')
  .then(res => res.json())
  .then(res => {
    console.log(res)
  })
           

參考:

繼續閱讀