前言
本文基于 react (“react”: “^16.13.1”) , express(“express”: “~4.16.1”,);
有一定的express了解,并能写简单的接口。
1.定义一个接口
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/users', function(req, res, next) {
let itemArr = [
{ username: 'Keely' },
{ username: '敖丙' },
{ username: '晨曦时梦见兮' },
{ username: '神三元' },
{ username: '冴羽' },
{ username: 'jsonchao' },
{ username: '夜幕降临耶' },
{ username: '给我点阳光就灿烂' },
{ username: '沉默王二' },
{ username: '_yuanhao' },
{ username: '芦半山' }
];
// 数据处理
let data = [];
// 页数
let page = req.query.page;
// 条数
let pageSize = req.query.pageSize;
// 计算返回的条数
let len = (1000 - pageSize * (page - 1)) < pageSize ? (1000 - pageSize * (page - 1)) : pageSize;
for (i = 0; i < len; i++) {
// 随机返回数组一项
let n = Math.floor(Math.random() * itemArr.length + 1) - 1;
data.push(itemArr[n]);
}
// 模拟延迟返回数据
setTimeout(() => {
res.json({
data
});
}, 500);
});
module.exports = router;
2.使用
以下代码进行了前端代理配置
前端代理配置,具体配置请看另一篇文章 react axios配置代理(proxy),解决本地开发时的跨域问题
import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
componentDidMount() {
axios.get('/api/users', {
params: {
page: 1,
pageSize: 10
}
})
.then(res => {
console.log(res);
})
// 在3秒钟后模拟分页再次被请求
setTimeout(() => {
axios.get('/api/users', {
params: {
page: 1,
pageSize: 6
}
})
.then(res => {
console.log(res);
})
}, 3000);
}
}
export default App;
3.效果图
4.服务端返回public文件夹里的图片方法
express脚手架已经默认配置过了静态文件路径
// app.js
app.use(express.static(path.join(__dirname, 'public')));
查询服务端端口号(如下面的9000就是端口号)
// bin -> www文件下
var port = normalizePort(process.env.PORT || '9000');
使用,http://localhost: 端口号 就可以加载 public目录,后面直接跟上路径
http://localhost:9000/images/1.jpg
也可以给静态资源文件创建一个虚拟的文件前缀(实际上文件系统中并不存在) ,可以使用 express.static 函数指定一个虚拟的静态目录,就像下面这样:
// app.js
app.use('/static', express.static(__dirname + '/public'));
使用如下
http://localhost:9000/static/images/1.jpg
如果本篇文章对你有帮助的话,很高兴能够帮助上你。
当然,如果你觉得文章有什么让你觉得不合理、或者有更简单的实现方法又或者有理解不来的地方,希望你在看到之后能够在评论里指出来,我会在看到之后尽快的回复你。