最近安装了下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:/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 分页请求的更多相关文章

  1. android项目中配置NDK自动编译生成so文件

    1 下载ndk开发包   2 在android 项目中配置编译器(以HelloJni项目为例)  2.1 创建builer  (a)Project->Properties->Builder ...

  2. ckeditor编辑器在java项目中配置

    一.基本使用: 1.所需文件架包 A. Ckeditor基本文件包,比如:ckeditor_3.6.2.zip 下载地址:http://ckeditor.com/download 2.配置使用 A.将 ...

  3. C# 在项目中配置Log4net

    我们介绍一下在项目中配置log4net,是Apache基金会旗下的. 无论在什么环境中,配置log4net的逻辑都一样. 1)文件配置 首先在项目加载文件中,配置log4net加载项. 在Web项目中 ...

  4. WebCollector2.7爬虫框架——在Eclipse项目中配置

    WebCollector2.7爬虫框架——在Eclipse项目中配置 在Eclipse项目中使用WebCollector爬虫非常简单,不需要任何其他的配置,只需要导入相关的jar包即可. Netbea ...

  5. 在maven项目中 配置代理对象远程调用crm

    1 在maven项目中配置代理对象远程调用crm 1.1 在项目的pom.xml中引入CXF的依赖 <dependency> <groupId>org.apache.cxf&l ...

  6. web项目中配置多个数据源

    web项目中配置多个数据源 spring + mybatis 多数据源配置有两种解决方案 1.配置多个不同的数据源,使用一个sessionFactory,在业务逻辑使用的时候自动切换到不同的数据源,  ...

  7. 如何在web项目中配置Spring的Ioc容器

    在web项目中配置Spring的Ioc容器其实就是创建web应用的上下文(WebApplicationContext) 自定义要使用的IoC容器而不使用默认的XmlApplicationContext ...

  8. Spring-Boot项目中配置redis注解缓存

    Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...

  9. 在Vue&Element前端项目中,使用FastReport + pdf.js生成并展示自定义报表

    在我的<FastReport报表随笔>介绍过各种FastReport的报表设计和使用,FastReport报表可以弹性的独立设计格式,并可以在Asp.net网站上.Winform端上使用, ...

随机推荐

  1. Python:游戏:300行代码实现俄罗斯方块

    本文代码基于 python3.6 和 pygame1.9.4. 俄罗斯方块是儿时最经典的游戏之一,刚开始接触 pygame 的时候就想写一个俄罗斯方块.但是想到旋转,停靠,消除等操作,感觉好像很难啊, ...

  2. Java学习路线图分析

     Java学习路线分析图 第一阶段 技术名称 技术内容 J2SE(java基础部分) java开发前奏 计算机基本原理,Java语言发展简史以及开发环境的搭建,体验Java程序的开发,环境变量的设置, ...

  3. Yii2设计模式——工厂方法模式

    应用举例 yii\db\Schema抽象类中: //获取数据表元数据 public function getTableSchema($name, $refresh = false) { if (arr ...

  4. vue 中使用promise

    init1(){return new Promise((resolve, reject) => { let data={ dateStr:this.time }; api.get('url', ...

  5. 联发科MT8788基带处理器介绍

    MT8788设备具有集成的蓝牙.fm.wlan和gps模块,是一个高度集成的基带平台,包括调制解调器和应用处理子系统,启用LTE/LTE-A和C2K智能设备应用程序.该芯片集成了工作在2.0GHz的A ...

  6. 安卓开发笔记(二十四):手把手教你一步步集成腾讯X5内核(Tencent TBS X5)

    1.为什么要集成腾讯X5内核? X5内核相对于系统webview,具有下述明显优势: 1) 速度快:相比系统webview的网页打开速度有30+%的提升: 2) 省流量:使用云端优化技术使流量节省20 ...

  7. Android之greenDao使用

    文章大纲 一.greenDao简介二.greenDao实战三.项目源码下载四.参考文章   一.greenDao简介 1. 什么是greenDao   GreenDAO是一个开源的Android OR ...

  8. nginx 安装、启动、重启、关闭 (linux系统命令行)

    前言: 最近在部署我的hexo静态博客到腾讯云服务器上,用到了很多nginx的知识,在此做下总结: 刚接触的linux服务器上,nginx配置乱的有点令人发指,就把老的卸载了重新装一下. 1.卸载 y ...

  9. Implement heap using Java

    public class HeapImpl { private int CAPACITY = 10; private int size = 0; private int[] data; public ...

  10. Excel日期中那个著名的bug

    一个软件中的bug能够持续多久?答案不一,大多数bug在软件测试阶段就已经被干掉,又有许多死在Preview阶段,抑或正式上线后不久被干掉,有些则伴随软件终生,直到下一代产品发布才寿终正寝,而Exce ...