Skip to content

接口配置 ​

本节目标:理解“接口配置”的核心思路,并能把它用于实际开发或面试表达。

说明:原 OneNote 中有图片引用,但图片未包含在导出目录中;本页保留了可用的文字与代码内容。

在项目的开发过程中,我们也少不了与后台服务器进行数据的获取和交互,这一般都是通过接口完成的,那么我们如何进行合理的接口配置呢?我们可以在 src 目录下新建 services 文件夹用于存放接口文件:
==└──== ==src======    ==└──== ==services======        ==├──== ==http.js==      ==#== ==接口封装======        ==├──== ==moduleA.js==    ==# A====模块接口======        ==└──== ==moduleB.js==    ==# B====模块接口==
为了让接口便于管理,我们同样使用不同的文件来配置不同模块的接口,同时由于接口的调用 ajax 请求代码重复部分较多,我们可以对其进行简单的封装,比如在 http.js 中(fetch为例):
/* http.js */
import 'whatwg-fetch'
// HTTP 工具类
export default class Http {
  static async request(method, url, data) {
    const param = {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      }
    };
    if (method === 'GET') {
      url += this.formatQuery(data)
    } else {
      param['body'] = JSON.stringify(data)
    }
    // Tips.loading(); // 可调用 loading 组件
    return fetch(url, param).then(response => this.isSuccess(response))
      .then(response => {
        return response.json()
      })
  }
  // 判断请求是否成功
  static isSuccess(res) {
    if (res.status >= 200 && res.status < 300) {
      return res
    } else {
      this.requestException(res)
    }
  }
  // 处理异常
  static requestException(res) {
    const error = new Error(res.statusText)
    error.response = res
    throw error
  }
  // url处理
  static formatQuery(query) {
    let params = [];
    if (query) {
      for (let item in query) {
        let vals = query[item];
        if (vals !== undefined) {
          params.push(item + '=' + query[item])
        }
      }
    }
    return params.length ? '?' + params.join('&') : '';
  }
  // 处理 get 请求
  static get(url, data) {
    return this.request('GET', url, data)
  }
  // 处理 put 请求
  static put(url, data) {
    return this.request('PUT', url, data)
  }
  // 处理 post 请求
  static post(url, data) {
    return this.request('POST', url, data)
  }
  // 处理 patch 请求
  static patch(url, data) {
    return this.request('PATCH', url, data)
  }
  // 处理 delete 请求
  static delete(url, data) {
    return this.request('DELETE', url, data)
  }
}
封装完毕后我们在 moduleA.js 中配置一个 github 的开放接口:==https://api.github.com/repos/octokit/octokit.rb==
/* moduleA.js */
import Http from './http'
// 获取测试数据
export const getTestData = () => {
  return Http.get('https://api.github.com/repos/octokit/octokit.rb')
}
然后在项目页面中进行调用,会成功获取 github 返回的数据,但是一般我们在项目中配置接口的时候会直接省略项目 url 部分,比如:
/* moduleA.js */
import Http from './http'
// 获取测试数据
export const getTestData = () => {
  return Http.get('/repos/octokit/octokit.rb')
}
这时候我们再次调用接口的时候会发现其调用地址为本地地址:==http://127.0.0.1:8080/repos/octokit/octokit.rb==,那么为了让其指向 ==https://api.github.com==,我们需要在 vue.config.js 中进行 devServer 的配置:
/* vue.config.js */
module.exports = {
  ...
  devServer: {
  // string | Object 代理设置
  proxy: {
    // 接口是 '/repos' 开头的才用代理
    '/repos': {
      target: '[https://api.github.com](https://api.github.com)', // 目标地址
        changeOrigin: true, // 是否改变源地址
              // pathRewrite: {'^/api': ''}
          }
  },
}

  ...
}
在 devServer 中 我们配置 proxy 进行接口的代理,将我们本地地址转换为真实的服务器地址,此时我们同样能顺利的获取到数据,不同点在于接口状态变成了 304(重定向):

本站总访问 — 次