分类 异常 下的文章

在学些Vue时,使用Mock Server模拟数据时,出现的问题,这里记录下最后的解决办法。
先说下,我的操作:
1、在项目根目录创建mock目录,再创建mock/mock-server.js,mock-server.js就只做了 app.get ,app.post等请求,加了个文件热加载。

const chokidar = require('chokidar')
const bodyParser = require('body-parser')
const chalk = require('chalk')
const path = require('path')

const mockDir = path.join(process.cwd(), 'mock')

function registerRoutes(app) {
  let mockLastIndex
  const { default: mocks } = require('./index.js')
  for (const mock of mocks) {
    app[mock.type](mock.url, mock.response)
    mockLastIndex = app._router.stack.length
  }
  const mockRoutesLength = Object.keys(mocks).length
  return {
    mockRoutesLength: mockRoutesLength,
    mockStartIndex: mockLastIndex - mockRoutesLength
  }
}

function unregisterRoutes() {
  Object.keys(require.cache).forEach(i => {
    if (i.includes(mockDir)) {
      delete require.cache[require.resolve(i)]
    }
  })
}

module.exports = app => {
  // es6 polyfill
  require('@babel/register')

  // parse app.body
  // https://expressjs.com/en/4x/api.html#req.body
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({
    extended: true
  }))

  const mockRoutes = registerRoutes(app)
  var mockRoutesLength = mockRoutes.mockRoutesLength
  var mockStartIndex = mockRoutes.mockStartIndex
  console.log(chalk.magentaBright(`\n > Mock Server Start success! `))
  // watch files, hot reload mock server
  chokidar.watch(mockDir, {
    ignored: /mock-server/,
    ignoreInitial: true
  }).on('all', (event, path) => {
    if (event === 'change' || event === 'add') {
      try {
        // remove mock routes stack
        app._router.stack.splice(mockStartIndex, mockRoutesLength)

        // clear routes cache
        unregisterRoutes()

        const mockRoutes = registerRoutes(app)
        mockRoutesLength = mockRoutes.mockRoutesLength
        mockStartIndex = mockRoutes.mockStartIndex

        console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed  ${path}`))
      } catch (error) {
        console.log(chalk.redBright(error))
      }
    }
  })
}

2、通过webpack的devServer 启动,并配置代理(将接口请求地址 代理到 mock/)

       const port=9527
      devServer: {
        port: port,
        open: true,
        overlay: {
          warnings: false,
          errors: true
        },
        proxy: { // 代理      
          ['/']: {
            target: `http://127.0.0.1:${port}/mock`,
            changeOrigin: true,
            pathRewrite: {
              ['^' + process.env.VUE_APP_BASE_API]: ''
            }
          }
        },
        after: require('./mock/mock-server.js') // 启动mock-server
      }

遇到过的错误如下:

1、不能代理到/mock,错误提示如下

Proxy error: Could not proxy request /user/info from localhost:2000 to http://127.0.0.1:2000/mock.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

这个问题通常都是Mock Server 启动失败
一般是端口被占用,如果用到 process.env.port || process.env.npm_config_port 变量,注意系统变量中的是否设置过port,如果设置了,最好清除或不适用此变量。
并且记得改过以后一定要重启终端(最好重新打开)。

2、数据返回的不对
这个问题是在能获取到数据,但获取不是想要的数据。通常是因为启动了多个项目,且项目没有设置统一端口(或端口冲突),只需要给定不同的端口即可

3、get请求无效
这个问题是能获取数据,Post请求正常,但get请求时只能获取到一段index.html代码,不是有效数据,
这个一般只需要在请求的header中设置Accept为 application/json, text/plain, */* 就能解决