前言
本文基於 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
如果本篇文章對你有幫助的話,很高興能夠幫助上你。
當然,如果你覺得文章有什麼讓你覺得不合理、或者有更簡單的實現方法又或者有理解不來的地方,希望你在看到之後能夠在評論裏指出來,我會在看到之後儘快的回覆你。