当用create-react-app创建好项目,启动后会自动打开 localhost:3000。 我们希望当访问 localhost:3000/api/todo 会向后台发起一个请求,拿到我们想要的 json 数据。并渲染到前台。 这样的话需要先创建一个后台服务器。我们使用NodeJS的 express 或 koa 服务器框架。下面以 koa 为例。
实现方法如下:
yarn add koa koa-router
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',
}
]
"proxy": "http://localhost:4000",
这样当我们在create-react-app的代码里调用fetch('api/todos')
会被代理执行http://localhost:4000/api/todos
并且在 script 节点下添加
"mock": "node ./mock/server.js"
这样执行 yarn mock
就启动了这个后台服务fetch('/api/todos')
.then(res => res.json())
.then(res => {
console.log(res)
})
参考: