1. 程式人生 > >在 vue cli3 的項目中配置雙服務,模擬 ajax 分頁請求

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

new css listen -m dir ble col export code

最近安裝了下vue cli3版本,與 cli 2 相比,文件少了,以前配置方法也不管用了。demo 中的大量的數據,需要做成 ajax 請求的方式來展示數據,因此,需要啟動兩個服務,一個用作前端請求,一個用作後端發送。

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

在安裝成功 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 / fs

npm install body-parser 
npm i fs

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

/**新配置的 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.

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

技術分享圖片

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

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

dev: {

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

重新啟動服務:npm run dev,再次請求

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;
        })
  }
}

完。

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