关于Vue使用Mock接口报404的问题

初次在Vue中使用Mock的时候,引用了网上的常用做法:在根目录的vue.config.js文件下引用:

module.export = {
    lintOnSave: false,
    devServer: {
        // before: require('./mock/index.js')
        before(app) {
            console.log('before ')
            app.get("/user/info", (rep, res) => {
                console.log('in mock')
                var json = {
                    name: 'hh',
                    age: 24
                }
                res.json(Mock.mock(json))
            })
        }
    }
}

但最终不管我怎么引用,都无法正常调用接口*/user/info*,总是报404。

尝试了很久,终于发现我的启动命令 npm run dev中 ,在package.json中的命名是:

scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "unit": "jest --config test/unit/jest.conf.js --coverage",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run unit && npm run e2e",
    "build": "node build/build.js"
  },

因此我直接找到webpack.dev.conf.js文件,添加:

before: app => {
      console.log('before ')
        app.get("/user/info", (rep, res) => {
            console.log('in mock')
            var json = {
                name: 'hh',
                age: 24
            }
            res.json(Mock.mock(json))
        })
    }

添加位置在:

// cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    },
    before: app => {
      console.log('before ')
        app.get("/user/info", (rep, res) => {
            console.log('in mock')
            var json = {
                name: 'hh',
                age: 24
            }
            res.json(json)
        })
    }
    
  },
  plugins: [

然后再调用接口*/user/info*,调用正常

Logo

前往低代码交流专区

更多推荐