Axios

目录

一、安装Axios

二、发送请求

(一)Get请求

(二)Post请求

1. 第一种方式

2. 第二种方式

三、拦截器

(一)请求前拦截器

(二)应答拦截器

四、封装


一、安装Axios

npm i axios

-g 全局安装

在要用的模块中导入axios

import axios from 'axios'

二、发送请求

(一)Get请求

// 请求头携带参数,案例:?uid=1001
axios.get(
    'http://localhost:8080/user/api/v1/user/query', {
        params: {
            uid: '1001'
        }
    }).then(res => {
    console.log(res.data)
}).catch(err => {
    console.log("请求错误=" + err)
}).finally(() => {

})

(二)Post请求

1. 第一种方式

function funPost() {
    // 请求体携带参数
    axios.post(
        'http://localhost:8080/user/api/v1/user/query',
        'uid=1001'
    ).then(res => {
        console.log(res.data)
    }).catch(err => {
        console.log("请求错误=" + err)
    }).finally(() => {

    })
}

2. 第二种方式

后端需要使用@RequestBody User user注解

接收json转为对象

function funPost() {
    // 请求体携带参数
    axios({
        url: 'http://localhost:8080/user/api/v1/user/query',
        method: 'post',
        data: {
            'id': '1001'
        }
    }).then(res => {
        console.log(res.data)
    }).catch(err => {
        console.log("请求错误=" + err)
    }).finally(() => {

    })
}

三、拦截器

(一)请求前拦截器

// 请求前拦截器
axios.interceptors.request.use(function (config) {
    config.url = config.url + "?token=ABC"
    return config
}, function (err) {
    return Promise.reject(err)
})

(二)应答拦截器

五、Axios全局默认值

axios.defaults.baseURL = 'http://localhost:8000'
axios.defaults.timeout = 5000
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

四、封装

路径:@/api/httpRequest.js        @是src的目录

import axios from "axios";

// 设置默认值
axios.defaults.baseURL = 'http://localhost:8000/api'
axios.defaults.timeout = 7000

// get
function doGet(url, params) {
    return axios({
        url: url,
        method: 'get',
        params: params
    })
}

// post
function doPost(url, params) {
    return axios({
        url: url,
        method: 'post',
        params: params
    })
}

// 暴露方法
export {doGet, doPost}

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋劲豪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值