关于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*,调用正常

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐