# 网络

# 接口路径配置

每个页面下都有一个api.js文件,本页面使用的接口地址都配置在此文件中,通过common/api/url.js文件统一引入,并在main.js中挂载到公共变量global

  • 如下所示:
export default {
const publicApi = {
  publicUpdateAPP: '/v1/5f3de8d284639', // 静默更新
  postRecommentGoods: '/v1/5fd9a32379116', // 智能推荐

}
const modulesFiles = require.context('../../pages/',true,/\api.js$/);
const modules = modulesFiles.keys().reduce((modules,modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/,'$1');
  const value = modulesFiles(modulePath);
  Object.assign(modules,value.default);
  return modules;
},publicApi);

export default modules;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 发起一个 GET 请求

export default {
  data() {
    return {};
  },

  onLoad() {
    this.$api
      .get(global.apiUrls.postWorkLike, {
        // 传入参数
      })
      .then(res => {
        // 接口请求成功做些什么
      })
      .catch(err => {
        // 接口请求失败做些什么
      });
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 发起一个 POST 求

export default {
  data() {
    return {};
  },

  onLoad() {
    this.$api
      .post(global.apiUrls.postWorkLike, {
        // 传入参数
      })
      .then(res => {
        // 接口请求成功做些什么
      })
      .catch(err => {
        // 接口请求失败做些什么
      });
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 如何在发起请求时候改变请求头

export default {
  data() {
    return {};
  },

  onLoad() {
    this.$api
      .post(
        global.apiUrls.postWorkLike,
        {
          // 传入参数
        },
        {
          header: {
            "Content-Type": "application/json"
          }
        }
      )
      .then(res => {
        // 接口请求成功做些什么
      })
      .catch(err => {
        // 接口请求失败做些什么
      });
  }
};
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

# 常见问题

  • Q: 如何改变请求时传入的全局 user-token 等公共信息?
    • A: 在/common/api/index.js 中配置
  • Q: 如何处理接口状态码?
    • A: 在/common/api/request.js 中管理,不建议修改,如果因前后端约定需要修改请参阅 request.js 源码自行修改