在旧版本的vue-cli中是在build目录下dev-sever.js中添加数据接口
vue-cli升级到2.9.1之后,把webpack升级到了v3.6.0,里边去掉了dev-server和dev-client两个文件,改在webpack.dev.conf.js设置

1、找到build文件夹

2、找到文件,webpack.dev.conf.js文件

3、找到const portfinder = require('portfinder')这句话添加下面代码

const axios = require('axios');
const express = require('express');
const apiRoutes = express.Router();

4、找到const devWebpackConfig=merge(baseWebpackConfig,{}里面的devServer添加代码

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // 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方法
    before (apiRoutes) {
      apiRoutes.get('/api/getDiscList', (req, res) => {
        // 这里是要链接的api地址
        const url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg';
        axios.get(url, {
          headers: {
            // 配置api地址referer
            referer: 'https://c.y.qq.com/',
            // 配置api地址host
            host: 'c.y.qq.com'
          },
          params: req.query  // 这是请求的query 
        }).then((response) => {
          // response是api地址返回的,数据在data里。
          res.json(response.data)
        }).catch((e) => {
          console.log(e);
        })
      });
      app.use('/api', apiRoutes);
    }
  }

moxiaojing
121 声望10 粉丝