axios在Vue中的简单使用

  1. 什么是Axios
    Axios是一个基于promise的HTTP客户端,用于浏览器和Node.js. Axios可以轻松地向REST API端点发送异步HTTP请求并执行CRUD操作。它可以在纯JavaScript中使用,也可以与Vue或React等库一起使用。

  2. 添加axios到项目

npm install axios --save
  1. axios 的简单使用
  • 简单Get请求
const axios = require('axios');

axios.get('http://webcode.me').then(resp => {

    console.log(resp.data);
});
  • Axios使用async/ wait获得请求
const axios = require('axios');

async function makeHeadRequest() {
  
  let res = await axios.head('http://webcode.me');
  
  console.log(`Status: ${res.status}`)
  console.log(`Server: ${res.headers.server}`)
  console.log(`Date: ${res.headers.date}`)
}

makeHeadRequest();
  • Axios API
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me'
    }

    let res = await axios(config)

    console.log(res.status);
}

makeRequest();
  • Axios 自定义 header
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me',
        headers: { 'User-Agent': 'Console app' }
    }

    let res = await axios(config)

    console.log(res.request._header);
}

makeRequest();
  • Axios POST 请求
const axios = require('axios');

async function makePostRequest() {

    let res = await axios.post('https://jsonplaceholder.typicode.com/posts');

    console.log(`Status code: ${res.status}`);
    console.log(`Status text: ${res.statusText}`);
    console.log(`Request method: ${res.request.method}`);
    console.log(`Path: ${res.request.path}`);

    console.log(`Date: ${res.headers.date}`);
    console.log(`Data: ${res.data}`);
}

makePostRequest();
  • Axios 下载图片
const axios = require('axios');
const fs = require('fs');

var config = {
    responseType: 'stream'
};

let url = 'https://images.dog.ceo/breeds/setter-english/n02100735_4870.jpg';

async function getImage() {

    let resp = await axios.get(url, config);
    resp.data.pipe(fs.createWriteStream('image.jpg'));
}

getImage();
  • Axios 多个请求
const axios = require('axios');

async function makeRequests() {

    let [u1, u2] = await Promise.all([
        axios.get('https://api.github.com/users/janbodnar'),
        axios.get('https://api.github.com/users/symfony')
    ]);

    console.log(`Jan Bodnar: ${u1.data.created_at}`);
    console.log(`Symfony: ${u2.data.created_at}`);
}

makeRequests();
  • 带JSON参数的 Axios 请求
const axios = require('axios');

async function makePostRequest() {

    params = {
        id: 6,
        first_name: 'Fred',
        last_name: 'Blair',
        email: '[email protected]'
      }

    let res = await axios.post('http://localhost:3000/users/', params);

    console.log(res.data);
}

makePostRequest();
  • Axios配置
    baseURL:请求时会自动拼接上
    axios.defaults.baseURL = ' https://www.exp01.com/api';
    let url = /user/get';
    axios.get(url).then(res => {
        console.log(res);
    })
  1. 跨域访问
header('Access-Control-Allow-Origin:*');//允许所有来源访问 
header('Access-Control-Allow-Method:POST,GET');//允许访问的方式 
  1. 拦截器
    拦截器分为 请求(request)拦截器和 响应(response)拦截器
  • 创建一个axios实例
    // 创建axios对象
    let $axios = axios.create({
        baseURL: 'http://。。。'
    })
  • 请求(request)拦截器
    // 发送前拦截 request-请求
    $axios.interceptors.request.use(config => {
        // 添加请求头
        config.headers.sessionToken = 'asdfasdf234234234';
        return config;
    })

响应(response)拦截器

    // 数据返回后的拦截 response-响应
    $axios.interceptors.response.use(function (res) {
        if (res.data.code === '666') {
            return res.data;
        } else {
            alert(res.data.msg);
        }
    }, function (error) {
        alert('网络异常');
    })
  1. 结论
    本文介绍的是axios的一下基础用例。

你可能感兴趣的:(axios在Vue中的简单使用)