在 vue cli3 的項目中配置雙服務,模擬 ajax 分頁請求

最近安裝了下vue cli3版本,與 cli 2 相比,文件少了,之前配置方法也無論用了。demo 中的大量的數據,須要作成 ajax 請求的方式來展現數據,所以,須要啓動兩個服務,一個用做前端請求,一個用做後端發送。css

雙服務的配置方法在 build / webpack.dev.conf.js 中寫入。html

在安裝成功 vue 後,是僅有一個 端口爲 8080 的服務,默認的服務名稱爲:devServer,爲了知足兩個服務的需求,須要在這個文件中再配一個服務,服務名稱爲 : api-server前端

 

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,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

 

api-server 的服務須要用到 express / body-parser / fs,除了 express 不用安裝外,還須要安裝 body-parser / fsvue

npm install body-parser 
npm i fs

服務端的配置文件在 devServer 服務結束後:webpack

/**新配置的 api-server,用來使用 axios 分頁獲取數據
 * 
 * 1.須要使用 express 來新建並啓動服務,須要安裝 express / body-parser / fs / 
 * 2.port 的設置從 PORT || config.dev.port 中解析,由於 port 的解析存在於 config/index.js的 dev 中
 * 3.數據的地址經過 readFile()讀取,數據目錄同 src 同級
 * 4.api-server 的請求地址爲:http://localhost:8081/api/shop?page=1  必須加參數 page ,不然獲取不到數據
 * 
 * 5.請求的端口號爲 8080 ,服務端的端口號爲 8181
 */
const express=require('express')
const apiServer = express()
const bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
const apiRouter = express.Router()
const port = PORT || config.dev.port
const fs = require('fs')
apiRouter.route('/:apiName')
.all(function (req, res) {
  var page=req.query.page;
  //請求的數據地址
  fs.readFile('./db/data.json', 'utf8', function (err, data) {
    // if (err) throw err
    var data = JSON.parse(data)
    if (data[req.params.apiName]) {
      var result=data[req.params.apiName];
      //newData 爲請求數據的參數
      var newData=result.slice((page-1)*10,page*10);
      res.json(newData);
    }
    else {
      res.send('no such api name')
    }
  })
})

apiServer.use('/api', apiRouter);
apiServer.listen(port + 1, function (err) {
  if (err) {
    console.log(err)
    return
  }
  //dev-server默認端口爲8080,所以新建的server,端口號 +1 ,不會衝突
  console.log('Listening at http://localhost:' + (port + 1) + '\n')
});

當服務配置好後,須要重啓 npm run dev.ios

當前的請求端口爲8080,而服務端的端口爲8081,若是直接用下面的地址請求,無疑會發生跨域而請求失敗:git

const url = "http://localhost:8080/api/shop?page=";

 

解決跨域的辦法是,在 config / index.js / dev 的 proxyTable 對象中設置代理。當經過 8080 請求數據 /api/ 時,經過它指向數據來源 8081。github

dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    //設置代理,當請求 /api/ 時,指向 8081
    proxyTable: {
      '/api/':'http://localhost:8081/'
    },
}

從新啓動服務:npm run dev,再次請求 web

http://localhost:8080/api/shop?page=1 時,就能夠摸擬請求而獲取到第1頁的數據:
export default {
    data () {
    return {
      list: [],
      page:0
    }
  },
  mounted(){
      //結構加載完後,這裏寫請求數據的方法
        this.page++;
        axios.get(url + this.page).then(res=>{
            console.log('shopList=' + res.data)
            this.list = res.data;
        })
  }
}

完。ajax

相關文章
相關標籤/搜索