React下的axios应用总结

GET:

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  })
  .catch(function (error) {
    console.log(error);
  });

POST:

// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

在React中使用:

componentDidMount() {
    ajax_get('http://localhost:3000/',{'data':111},this,callback);
}

 

function ajax_post(url,data,that,callback){
    axios({
        method:"POST",
        headers:{'Content-type':'application/json',},
        url:URL+url,
        data:data,
        //withCredentials:true
    }).then(function(res){
        //alert('post:'+res)
        console.log(url+'\tPost请求到:');
        console.log(res);
        //alert('post-response:'+res);
        callback(that,res);
        //ajax_get('/manage/getinfo',this);
    }).catch(function(error){
        alert('post失败')
        console.log(error);
    });
}
function ajax_get(url,that,callback){
    axios({
        method:"GET",
        headers:{'Content-type':'application/json',},
        url:URL+url,
        withCredentials:true
    }).then(function(res){
        console.log(url+'\tGet请求到:')
        console.log(res);
        //alert('get:'+this.res);
        callback(that,res);

    }).catch(function(error){
        alert('get下载失败')
        console.log(error);
    });
}
function ajax_post_params(url,data,that,callback=()=>{}){
    axios({
        method: 'post',
        url: URL+url,
        headers: {
            'Content-type': 'application/x-www-form-urlencoded',
        },
        params:data,
    })
    .then(function(res){
        //alert('post:'+res)
        console.log(url+'\tPost请求到:');
        console.log(res);
        //alert('post-response:'+res);
        callback(that,res);
        //ajax_get('/manage/getinfo',this);
    }).catch(function(error){
        alert('post失败')
        console.log(error);
    });
}

错误问题:

交互时 URL 如果出现 http://localhost:3000/[object%20Object],需要判断ajax的语法是否有效,

作者:小幸运Q
链接:https://www.jianshu.com/p/c591a7214bee
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

React中封装axios可以通过创建一个通用的axios实例来实现。可以按照以下步骤进行操作: 1. 首先,安装axios库,可以通过运行`npm install axios`命令来安装。 2. 在你的项目中创建一个文件,比如`api.js`,用于封装axios请求。 3. 在`api.js`文件中引入axios库:`import axios from 'axios'`。 4. 创建一个axios实例:`const instance = axios.create({ baseURL: 'http://api.example.com' })`。这里的`baseURL`是你的API的基本URL,你可以根据实际情况进行修改。 5. 接下来,你可以在该实例上定义各种请求方法,比如`get`、`post`等:``` export const getArticleList = () => { return instance.get('/article/home/index') } ``` 6. 最后,你可以在你的React组件中引入这些封装好的请求方法,并使用它们来发送请求:``` import React, { useEffect } from 'react'; import { getArticleList } from './api'; const Home = () => { useEffect(() => { getArticleList().then(response => { console.log('get article response:', response); }).catch(error => { console.log('get response failed!'); }); }, []); return ( // 组件的内容 ); }; export default Home; ```这样,你就可以在React中封装axios并使用它来发送请求了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [react + ts or vue + ts 通用axios封装的方法。 ](https://download.csdn.net/download/qq_40661003/86247561)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【重点突破】—— React应用中封装axios(转)](https://blog.csdn.net/qq_34235864/article/details/113805369)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值