index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import Mock from 'mockjs'
  2. import mocks from './mocks'
  3. import { param2Obj } from '../src/utils'
  4. const MOCK_API_BASE = '/mock'
  5. export function mockXHR() {
  6. // 修复在使用 MockJS 情况下,设置 withCredentials = true,且未被拦截的跨域请求丢失 Cookies 的问题
  7. // https://github.com/nuysoft/Mock/issues/300
  8. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  9. Mock.XHR.prototype.send = function() {
  10. if (this.custom.xhr) {
  11. this.custom.xhr.withCredentials = this.withCredentials || false
  12. }
  13. this.proxy_send(...arguments)
  14. }
  15. function XHR2ExpressReqWrap(respond) {
  16. return function(options) {
  17. let result = null
  18. if (respond instanceof Function) {
  19. const { body, type, url } = options
  20. // https://expressjs.com/en/4x/api.html#req
  21. result = respond({
  22. method: type,
  23. body: JSON.parse(body),
  24. query: param2Obj(url)
  25. })
  26. } else {
  27. result = respond
  28. }
  29. return Mock.mock(result)
  30. }
  31. }
  32. for (const i of mocks) {
  33. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  34. }
  35. }
  36. const responseFake = (url, type, respond) => {
  37. return {
  38. url: new RegExp(`${MOCK_API_BASE}${url}`),
  39. type: type || 'get',
  40. response(req, res) {
  41. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  42. }
  43. }
  44. }
  45. export default mocks.map(route => {
  46. return responseFake(route.url, route.type, route.response)
  47. })