在搭建好react脚手架项目后(使用脚手架搭建项目的博客),我们经常会使用axios 发送请求与后端交互,下面是关于 axios 的使用的内容。
先安装axios:
npm install axios --save
在 src 目录下新建一个 server.js 的文件,代码如下:
import axios from 'axios'
import qs from 'qs'
import {message} from 'antd';
//对 get post方法 进行封装
let http = {
post:"",
get:""
};
axios.defaults.baseURL = '/api';
http.post=function (api,data) {
return new Promise((resolve,reject)=>{
//1、执行异步ajax请求
axios.post(api,data)
.then((res)=>{
//2、成功了调用resolve(value)
resolve(res)
})
//3、如果失败了提示异常信息
.catch(function(error){
message.error("请求出错:"+error.message);
})
})
};
http.get=function (api,data) {
return new Promise((resolve,reject)=>{
axios.get(api,{params:data})
.then((res)=>{
resolve(res)
})
.catch(function(error){
message.error("请求出错:"+error.message);
})
})
};
export default http
在react组件上使用 axios :
import http from "../../server" //引入
async getList(){
const res = await http.post('/login',{
userName:'xxx',
password:'123456'
})
console.log(res)
}
根据你的接口和要传参数自行更改其中部分代码。