zoukankan      html  css  js  c++  java
  • react中使用json-server mock数据

    我们需要使用json-server创建一个json的服务器,相当于后端,当我们前端使用axios请求数据时,返回接口文档中对应的字段

    最近在项目中需要数据测试,为了方便,直接引入mockjs。

    安装模块

    npm i json-server -g
    npm i axios -S

    首先在react-app/src下创建mock文件夹

    -src
    --mock
    ---mock.json
    ---route.json
    ---banner.json // 请求的数据也放在mock文文件中son

    banner.json数据示例

    {
        "code": "200",
        "message": "获取轮播图的数据",
        "data": [{
            "bannerid": "banner_1",
            "img": "https://m.360buyimg.com/mobilecms/s700x280_jfs/t1/89951/22/13835/67854/5e64a4b8E84c207d9/7367dad332fe905b.jpg!cr_1125x445_0_171!q70.jpg.dpg",
            "href": "",
            "alt": ""
        },{
            "bannerid": "banner_4",
            "img": "https://m.360buyimg.com/mobilecms/s700x280_jfs/t1/93827/39/13300/60640/5e561c60Edd0d8e34/73428f511893f63e.jpg!cr_1125x445_0_171!q70.jpg.dpg",
            "href": "",
            "alt": ""
        }]
    }

    mock.json

    const banner = require('./banner.json');
    module.exports = function() {
        return {
            banner
        }
    }

    route.json,配置路由

    {
        "/api/hotcate":"/hotcate",
        "/api/list":"/list",
        "/api/category":"/category"
    }

    在package.json文件中添加配置

    "scripts": {
        "mock": "json-server ./src/mock/mock.js --routes ./src/mock/route.json --port 9000 --watch"
      }// 使用npm run mock开启json服务器,如下图即为成功

    使用axios请求数据

    axios.get('http://localhost:9000/api/banner').then(res => {}) //就能得到数据

    可以将axios方法封装起来,当我们有了后端的数据之后,只需要替换‘http://localhost:9000’就可以了

  • 相关阅读:
    Voiceover “眼里” 的HTML5标签
    Edge浏览器默认地址被百度劫持
    How to fix "ReferenceError: primordials is not defined" error
    php 读文件
    jsconfig.json: Unexpected token ] in JSON at position
    公司入域电脑更新遇到 0x8024401c 解决办法
    颜色计算
    Terminal 美化
    highcharts 查看配置
    cra
  • 原文地址:https://www.cnblogs.com/shine1234/p/13219608.html
Copyright © 2011-2022 走看看