react结合axios
发起ajax请求
在项目根目录运行:
cnpm i axios -S
;安装axios包
用于测试的API地址:
get 请求地址: http://www.movie123.com:8081/api/getlunbo
post请求地址: http://www.movie123.com:8081/api/post
新建src/components/testAxios.jsx
import React from 'react'
export default class testAxios extends React.Component {
constructor(){
super()
// 组件私有数据
this.state = {
}
}
render(){
return <div>
<button onClick={()=>this.getInfo()}></button>
<button onClick={()=>this.postInfo()}></button>
</div>
}
// 实例方法
async getInfo() {
const {data} = await this.$http('/api/getlunbo')
console.log(data)
}
async cpostInfo() {
const result = await this.$http.post('/api/post',{
name: 'zs',
age: 23
})
console.log(result)
}
}
抽离全局配置文件globalConfig.js
- 全局配置请求的URL根路径
- 挂载 axios 之前,全局配置一下 transformRequest 参数即可。
transformRequest 作用:就是在发起post请求之前,对要发送给服务器的数据,做一层包装转换
function 中的data就是要发送给服务器的数据
import React from 'react'
import axios from 'axios'
// 全局配置请求的URL根路径
axios.defaults.baseURL = 'http://www.movie123.com:8081';
// 全局配置一下 transformRequest 参数
axios.defaults.transformRequest = [function(data,headers){
const arr = []
for(let key in data){
arr.push(key + '=' + data[key])
}
return arr.join('&')
}]
React.Component.prototype.$http = axios
在index.js页面中:
全局配置
axios
从而让每个组件都能直接调用axios
发起Ajax请求class 关键字 底层 也是由 普通 function 构造函数来实现的,因此 class 只是个语法糖
在每个 用 class 关键字 创建的 组件,都可以直接调用
this.$http
来发起Ajax请求
import React from 'react'
import ReactDOM from 'react-dom'
// 导入 axios
import '@/globalConfig.js'
// 导入 testAxios 组件
import testAxios from '@/components/testAxios'
ReactDOM.render(<div>
<testAxios></testAxios>
</div>, document.getElementById('app'))