React通过axios请求数据
一、全局安装axios:
npm install axios
二、创建axios.js文件(配置了过滤器,请求响应)
import Axios from 'axios'
import {Component} from 'react'
Component.prototype.$axios=Axios //将axios挂载到Component上,以供全局使用
//配置过滤器请求响应(通过查npm官网,axios文档)
Axios.interceptors.response.use(function (response) {
return response.data;//只获取data数据
}, function (error) {
return Promise.reject(error);
});
并在index.js中引入,import ‘相对路径/axios’
三、若出现跨域:
①最简单直接的方法:
在package.json中,直接配置:“proxy”:“http://47.95.207.1:8080”,
缺点:只能设置一个跨域,多个跨域不可取
②在config —> webpackDevServer.config.js中,找到proxy进行配置:
//设置跨域小暗号:/hehe
proxy:{
'/hehe':{
target:'http://47.95.207.1:8080',
changeOrigin:true,
pathRewrite:{'^/hehe':''}
}
},
四、在组件中请求数据:
componentDidMount(){
//请求api: http://47.95.207.1:8080/api/getHome 跨域小暗号:/hehe
this.$axios.get('/hehe/api/getHome')
.then((res)=>{
console.log(res)
})
.catch((err)=>{
console.log(err)
})
}