前后端通信
前后端通信通常使用 AJAX 方案,对于 AJAX 社区有非常多的封装,目前主流推荐 axios。
使用 axios 进行通信
安装依赖:npm install axios --save
通常情况下,AJAX 请求都是异步的,因此 axios 默认返回一个 Promise,因此你可以通过 Promise 或者 async/await 的方式调用:
import axios from 'axios';
// async/await 方式使用
async function getUser() {
try {
const response = await axios.get('/user', {
params: {
ID: 12345
}
});
console.log(response);
} catch (error) {
console.error(error);
}
}
// Promise 方式调用
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle network error
console.log(error);
})
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
// request query
params: {
foo: 'bar'
},
// request body
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 在 React 组件中使用
import React from 'react';
class Demo extends React.Component {
state = {
page: 1,
pageSize: 10,
total: 0,
dataSource: [],
}
componentDidMount() {
this.getData({page: 1, pageSize: 10})
}
getData(params) {
axios({
method: 'get',
url: '/api/getData',
params,
}).then(response => {
const { page, pageSize, total, dataSource } = res.data.data;
this.setState({ page, pageSize, total, dataSource });
});
}
render() {
const { dataSource, page, pageSize, total } = this.state;
return <div>...</div>
}
}
在这些基础功能基础上,axios 支持丰富的请求参数、异常状态码判断、全局处理异常、全局配置请求参数等,具体参见 axios 文档。