vue怎么结合axios实现restful风格

发布时间:2022-06-24 13:39:50 作者:iii
来源:亿速云 阅读:150

本篇内容主要讲解“vue怎么结合axios实现restful风格”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue怎么结合axios实现restful风格”吧!

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

axios其实和原生ajax,jquery中的$ajax类似,都是用于请求数据的,不过axios是基于promise的,也是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不是必须的,具体根据你请求发送的参数和后端定义的参数格式匹配即可)

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);
});

到此,相信大家对“vue怎么结合axios实现restful风格”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. SpringBoot整合swagger实现测试Restful风格api
  2. springmvc restful风格遇到的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue axios restful

上一篇:Element怎么使用el-table组件实现二次封装

下一篇:怎么用小程序实现轮播图

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》