vue axios实现restful风格请求

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue axios实现restful风格请求

坏丶毛病   2022-06-28 我要评论

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,基本请求有5种:

  • get:多用来获取数据
  • post:多用来新增数据
  • put:多用来修改数据(需要传递所有字段,相当于全部更新)
  • patch:多用来修改数据,是在put的基础上新增改进的,适用于局部更新,比如我只想修改用户名,只传用户名的字段就ok了,而不需要像put一样把所有字段传过去
  • delete:多用来删除数据

axios其实和原生ajax,jquery中的$ajax类似,都是用于请求数据的,不过axios是基于promise的,也是vue官方比较推荐的做法。

那么我们一起来看看具体在vue中的使用吧。

1、npm下载axios到vue项目中

这里解释一下为什么要下载qs,qs的作用是用来将请求参数序列化,比如对象转字符串,字符串转对象,不要小看它,会在后面有大用处的。

// npm下载axios到项目中
npm install axios --save
 
// npm下载qs到项目中
npm install qs.js --save

2、main.js里引入

记住这边使用axios时定义的名字,我定义的是axios,所以后续请求我也必须使用axios,当然你可以定义其他的,htpp,$axios,哪怕是你的名字都没关系,注意规范。

// 引入axios
import axios from 'axios'
// 使用axios
Vue.prototype.axios = axios;
 
// 引入qs
import qs from 'qs'
// 使用qs
Vue.prototype.qs = qs;

3、定义全局变量路径(不是必须的,但是推荐)

(1)、方法一

可在main.js里定义

// 右边就是你后端的每个请求地址公共的部分
// * : 地址是我瞎编的,涉及隐私,大家只要把每个请求地址一样的公共部分提出来即可
 
Vue.prototype.baseURL = "http://127.0.0.1:9000/api";

(2)、方法二

在config中的dev.env和prod.env中配置,在main.js里使用那两个文件的变量即可

①dev.env:本地环境

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
 
module.exports = merge(prodEnv, {
    NODE_ENV: '"development"',
    // 这里是本地环境的请求地址(请忽略地址,明白原理即可)
    API_ROOT: ' "http://localhost:8080/web" '
})

②prod.env:上线环境

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
 
module.exports = merge(prodEnv, {
    NODE_ENV: '"development"',
    // 这里是本地环境的请求地址(请忽略地址,明白原理即可)
    API_ROOT: ' "http://localhost:8080/web" '
})

③main.js中使用此路径

Vue.prototype.baseURL = process.env.API_ROOT;

4、在具体需求的地方使用

举个例子:

当我在登录页面点击登录,然后需要请求后台数据判断登录是否能通验证,以此来判断是否能正常登录,请求方法我写在methods里了,通过vue的@click点击事件,当点击登录按钮发起请求,然后通过vue的v-model绑定用户名和密码文本框的值,用来获取用户输入的值以便获取发送参数

之前我定义的变量是axios,所以这边使用this.axios发起请求,post是请求方式,而我需要把用户名和密码以字符串的形式发送,所以需要qs序列化参数(qs不是必须的,具体根据你请求发送的参数和后端定义的参数格式匹配即可)

  • .then是请求成功后的回调函数,response包含着后端响应的数据,可以打印看看
  • .catch是请求失败后的捕获,用来校验错误
login() {
 
    this.axios.post('http://bt2.xyz:8083/login/checkAdmin', qs.stringify({
          "username": this.userinfo.username,
          "password": this.userinfo.password
        }), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    })
    .then((response) => {
        console.log(response);
    })
    .catch((error) => {
        console.log(error);
    });
 
}

以上方法也可以这样写:

login() {
 
    this.axios({
        method:"post",
        url:"http://bt2.xyz:8083/login/checkAdmin",
        data:qs.stringify({
            "username": this.userinfo.username,
             "password": this.userinfo.password
        }),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    })
    .then((response) => {
        console.log(response);
    })
    .catch((error) => {
        console.log(error);
    });
 
}

注 : get、delete请求的参数是params(特殊情况可以直接跟在地址后面),而post、put、patch的参数是data

下面我们看看四种具体的请求方式吧 (忽略地址,涉及隐私所以就输了假的地址):

这里的${this.baseURL}就是我们前面定义的全局路径,只要在后面跟上变化的地址即可

这里的headers和qs不是必须的,因为我们业务需要传递这些数据,所以我才写的,大家只是参考格式即可

这里给出每种请求的两种写法,不尽相同,所以具体的请求还得看业务需求

put请求用的比较多,patch我自己用的很少,但是原理都是一样的,这里就不多说了

使用箭头函数是为了不改变this指向,方便后期处理数据

(1)、get

this.axios({
    method: "get",
    url:`${this.baseURL}/GetAll`,
    headers: {
        Account: "Admin",
        Password:"123456"
    }
})
.then((response)=> {
    console.log(response)
})
.catch((error)=> {
    console.log(error);
});
this.axios.get('http://bt2.xyz:8083/solr/adminQuery', {
    params: {
        "page": 1,
        "rows": 5
    }
})
 .then((response)=> {
    console.log(response)
})
.catch((error)=> {
    console.log(error);
});

(2)、post

this.axios({
    method:"post",
    url:`${this.baseURL}/Create`,
    headers: {
        Account: "Admin",
        Password:"123456"
    },
    data:qs.stringify({
        Title: this.addTitle,
        Host: this.addHost,
        Port: this.addPort,
        Account: this.addAccount,
        Password: this.addPassword,
        DbName: this.addDbName
    })
})
.then( (response)=> {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
login() {
 
    this.axios.post('http://bt2.xyz:8083/login/checkAdmin', qs.stringify({
          "username": this.userinfo.username,
          "password": this.userinfo.password
        }), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    })
    .then((response) => {
        console.log(response);
    })
    .catch((error) => {
        console.log(error);
    });
 
}

(3)、put

像这个请求,我就在地址栏后面追加了一个参数,id,只要后端格式允许,也可以这样做

this.axios({
    method:"put",
    url:`${this.baseURL}/Update/`+(this.Data[index].id),
    headers: {
        Account: "Admin",
        Password:"123456"
    },
    data:qs.stringify({
        Title: inputs[0].value,
        Host: inputs[1].value,
        Port: inputs[2].value,
        Account: inputs[3].value,
        Password: inputs[4].value,
        DbName: inputs[5].value
    })
})
.then( (response)=> {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
this.axios.put('http://bt2.xyz:8083/Goods/update', {
    "goodsId": goodsId,
    "goodsName": goodsName,
    "goodsPrice": goodsPrice,
    "goodsNum": goodsNum,
    "goodsKind": 1,
    "goodsWeight": goodsWeight
})
.then((response)=> {
    console.log(response)    
})
.catch((error)=> {
    console.log(error);
});

(4)、delete

this.axios({
    method:"delete",
    url:`${this.baseURL}/Delete/`+(this.Data[index].id),
    headers: {
        Account: "Admin",
        Password:"123456"
    }
})
.then((response)=> {
    console.log(error);
})
.catch((error)=> {
    console.log(error);
});
this.axios.delete('http://bt2.xyz:8083/Goods/delete?goodsId=' + this.ProductId)
.then((response)=> {
    console.log(response)                   
})
.catch((error)=> {
    console.log(error);
});

以上就是常用的四种restful风格的请求,都是博主自己开发中请求的数据,都没问题,但是具体的请求还要看大家和后端数据格式的规范以及一些业务熟悉,这里只提供思路。如有错误或未考虑完全的地方,望不吝赐教。希望大家多多支持。

切记跨域问题,记得让后端处理,如果是本地的话,可以参考vue的代理

这里附上axios的官方文档,提供大家参考。axios中文官方文档

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们