Skip to content

Latest commit

 

History

History
60 lines (45 loc) · 1.92 KB

前端如何接入使用?.md

File metadata and controls

60 lines (45 loc) · 1.92 KB

前端如何接入使用

本文档是基于服务地址为 http://127.0.0.1:3007 来说明,本地服务启动命令 npm start

一、host 映射方式

  1. 配置 host 映射,接口地址 api.example.com 到本地服务地址 127.0.0.1
  2. 本服务根据 hostname 识别出使用哪个 mock 数据
  3. 直接访问 http://api.example.com:3007 即可使用 mock 数据
  4. 使用 80 端口可以更简便,不用更改原接口配置直接使用

host 映射

127.0.0.1 api.example.com

api.example.com 域名只是举例,具体视实际使用的

二、请求头传参方式

  1. 插入脚本更改代码,可以拦截 ajax 请求,增加自定义处理
  2. 拦截请求替换域名为本服务地址 http://127.0.0.1:3007
  3. 拦截请求增加请求头 x-mock-domain: '{原接口域名}'
  4. 本服务根据请求头识别使用哪个 mock 数据
  5. 使用时选择多种方式开启,url 参数、请求 body、页面参数,追加 __mock__=1

例如使用 fetch 请求接口,可以插入如下脚本拦截请求

let _fetch = globalThis.fetch
globalThis.fetch = function(url, params) {
  if(isFromMock(url, params)) {
    let domains = /^https?:\/\/(.+?)\/.*/.exec(url)
    if (domains) {
      let domain = domains[1]
      url = url.replace(domain, 'http://127.0.0.1:3007')
      params.headers['x-mock-domain'] = domain
      console.log(['__MOCK__', url])
    }
  }

  return _fetch(url, params)
}

let reg_mock = /__mock__/i
function isFromMock(url, params) {
  return reg_mock.test(url) || (params && reg_mock.test(params.body)) || reg_mock.test(location.search)
}

三、接入 sdk(fetch版)

  1. 页面中直接引入 js sdk,http://127.0.0.1:3007/static/sdk/fetch.intercept.js
  2. 使用时选择多种方式开启,url 参数、请求 body、页面参数,追加 __mock__=1
<script src="http://127.0.0.1:3007/static/sdk/fetch.intercept.js"></script>