react中使用json-server mock数据

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

安装模块

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

首先在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/*" : "/$1"
}

在package.json文件中添加配置

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

react中使用json-server mock数据_第1张图片
使用axios请求数据

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

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

你可能感兴趣的:(react)