服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - vue设置全局访问接口API地址操作

vue设置全局访问接口API地址操作

2021-08-24 16:07听闻如故 JavaScript

这篇文章主要介绍了vue设置全局访问接口API地址操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在使用vue框架进行前后端分离项目开发时,通常涉及到与后段接口进行交互,平时一般使用比较多的就是用axios来实现调用后段接口,写法一般为

?
1
2
3
4
5
6
xxx() {
   const _this = this
   axios.get("http://ip:port/xx/xx").then(function (resp) {
         .....//省略
   })
 }

但是有一个比较普遍的问题就是,假如我们后端接口地址改变了,或者是网络地址发生了变化,就需要在上面IP以及端口的位置每一处都需要修改,所以我们需要一个一处设置 处处可用的配置,如下

在src目录下新建interface文件夹,新建index.js文件

?
1
2
3
4
5
6
7
//配置全局访问接口地址
let commonUrl = "http://ip:port";
 
let baseUrl = {
  commonUrl
}
export default baseUrl

在main.js中引入上述配置

import api from "./interface/index" Vue.prototype.$api = api.commonUrl

接下来在原axios调用接口的位置稍作修改即可实现正常调用接口了

?
1
2
3
4
5
6
7
xx() {
       const _this = this
       axios.get(this.$api + "/xx/xx").then(function (resp) {
           .....
         }
       })
     }

补充知识:vue项目:(全局变量设置与调用)API接口封装 - 代码篇

vue项目,如何将“API接口” 封装为“全局变量” ?

1. API全局配置文件【global.vue文件】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
   <div> </div>  
</template>
 
 
<!-- API全局变量 -->
<script> 
  // 本地 接口地址
  const localSrc = 'http://192.168.0.103:8444';
  // 线上 接口地址
  const serverSrc = 'http://www.xxxxxx.com:8080/jobs-api';
 
  export default{
    localSrc,
    serverSrc
  }
</script>
 
<style>
</style>

2. 全局注册引入文件 【main.js文件】

?
1
2
3
// 引入API接口文件
import global_ from './components/api/global'//引用文件
Vue.prototype.GLOBAL = global_//挂载到Vue实例上面

3. 如下代码片段:【注释1、注释2、注释3】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
methods: {
   ajaxLoginApi: function (form) {  
  var that=this.form; // 放置指针,便于then操作的获取   
  console.log("账号"+that.username+"密码"+that.pwd);
 
  // var localPath = 'http://192.168.0.103:8444';
    // var ecsPath = 'http://www.1688jobs.com:8080/jobs-api/'
    
    var localPath = this.GLOBAL.localSrc; // 本地 接口地址 【注释1】
    var serverPath = this.GLOBAL.serverSrc; // 线上 接口地址【注释2】
    
  axios.post( serverPath + '/login',   // 【注释3】
     {
    // 'userName':'17681135201',
   // 'userPwd':'123456',
      // 'userType':"2"     
    'userName': this.form.username,
   'userPwd': this.form.pwd,
   'userType':"2"
   },
   {
   headers: {
    'Content-Type':'application/json',
    //'Authorization':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiI1QUZFRkQ4NTNFNjIwNDIyOEIwNDE3MzdCMDdBNEJCNURDNTBEQjA4OUFCQzBENDM4MDA5RkM4REU4QkMyODkzIiwidXNlck5hbWUiOiIxNzY4MTEzNTIwMSIsInVzZXJBZ2VudCI6Ik1vemlsbGEvNS4wIChXaW5kb3dzIE5UIDEwLjA7IFdpbjY0OyB4NjQpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS82OC4wLjM0NDAuMTA2IFNhZmFyaS81MzcuMzYiLCJleHAiOjE1NTE5MzYzODQsIm5iZiI6MTU1MTkzNDU4NH0.YgRW-Wnlk_Gz64id_jTocH68oj8DuZuI1WyQBmmrt7c'
   }
   },
  )
  .then(function (response) {
      console.log("response="+response);
      console.log("responseheader="+response.headers);
   var reslutData = response;
      // console.log(reslutData.data.code); 
      // 登录账号和密码 检测
      if (reslutData.data.code == 2006) { // 用户名不存在
       this.$notify.error({
        title: reslutData.data.message,
        duration: 2000
       });
       return false;
      }
      if (reslutData.data.code != 200) { // 登录失败
       this.$notify.error({
        title: reslutData.data.message,
        duration: 2000
       });
       return false;
      } else { // 登录成功
 
       // 弹框成功提示
       this.$notify({
        title: reslutData.data.message,
        // message: '正在跳转中···',
        type: 'success',
        duration: 2000
       });
 
       console.log("token=" + reslutData.data.data.token)
       // token写入本地客户端存储
       localStorage.setItem("token",reslutData.data.data.token);
       // token获取本地客户端存储
       // var key = localStorage.getItem("token");
       // console.log("key=" + key)
 
       // 成功之后执行跳转  this.$router.replace 
       this.$router.replace('/search');
 
      }
      
   
  }.bind(this))
  .catch(function (error) {
   console.log("请求失败"+error);
  });
 
  },

以上这篇vue设置全局访问接口API地址操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/gl19980514/article/details/107297575

延伸 · 阅读

精彩推荐