axios 的基本使用

axios的基本介绍

一、axios的介绍:

官方网站:http://www.axios-js.com

概念:aixos是一个基于Promise(ES6语法中用于处理异步的)的HTTP库,用于浏览器和node.js中。

作用
浏览器中创建XMLHttpRequests
从node.js中创建http请求
支持Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换JSON数据
客户端支持防御XSRF

安装命令:npm install axios
使用:import axios from ‘axios’

二、发送基本请求

get请求:

axios对象调用get方法,.then()成功回调,.catch()失败回调。

const axios = require('axios');
​
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

post请求:

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

通用的请求:

axios({
  methods: 'post',
  url: 'http://127.0.0.1:8000/users/',
  data: {
  name: 'qiurx'
  })
  .then(res=>{
    console.log(res.data);
  })
  .catch(function (error) {
    console.log(error);
  })

三、axios创建实例

let instance = axios.create({
	url:'http://127.0.0.1:8000/users/',
	imeout:3000,
	method:'post'
});
//即可调用方法,和axios实例同

instance.get('http://jsonplaceholder.typicode.com/users').then(Response=>{
   console.log(Response);
});

四,axios的请求拦截器和响应拦截器的使用

可以先拦截请求或响应,然后再由then 或处理catch。

// Add a request interceptpr
axios.interceptors.request.use(function(config){
	// Do something before request is sent
	return config;
}

)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值