在使用vue开发过程中,难免需要去本地数据地址进行请求,而原版配置在dev-server.js中,新版vue-webpack-template已经删除dev-server.js,改用webpack.dev.conf.js代替,所以 配置本地访问在webpack.dev.conf.js里配置即可。

  现在我们就来用node里的express来解决本地数据请求的问题。主要为下面三步:安装express和resource、注册并使用vue-resource、配置express并设置路由规则

  1、安装node的express,和vue-resource

  2、注意: 这里安装vue-resource后需要在main.js注册并使用下

import VueResource from 'vue-resource'
Vue.use(VueResource)

  3、在webpack.dev.conf配置express并设置路由规则

#webpack.dev.conf.js
// 首先在const portfinder = require('portfinder')后添加 // nodejs开发框架express,用来简化操作
const express = require('express')
// 创建node.js的express开发框架的实例
const app = express()
// 引用的json地址
var appData = require('../data.json')
// json某一个key
var goods = appData.result var apiRoutes = express.Router()
app.use('/api', apiRoutes)

  (1)get请求配置

#webpack.dev.conf.js
// 在devServer选项中添加以下内容
before(app) {
app.get('/api/someApi', (req, res) => {
res.json({
// 这里是你的json内容
})
})
}

  注意: 修改配置文件完毕后,需要重新运行命令npm run dev即可。

  (2)post请求配置。如果要配置post请求,需要在该文件夹配置如下:

#webpack.dev.conf.js
apiRoutes.post('/foods', function (req, res) { //注意这里改为post就可以了
res.json({
error: ,
data: foods
});
})
// 在组件里面
#...vue
created () {
this.$http.post('http://localhost:8080/api/foods').then((res) => {
console.log(res)
})
}

  (3)完整配置

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder') const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT) //增加express --start
const express = require('express')
const app = express()
var appData = require('../goods.json')
var goods = appData.goods
var apiRoutes = express.Router()
app.use('/api', apiRoutes)
//增加express --end 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,
},
//增加express --start
before(app) {
app.get('/api/goods', (req, res) => {
res.json({
code: 0,
data: goods
})
})
}
//增加express --end
},
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: ['.*']
}
])
]
}) module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
})) resolve(devWebpackConfig)
}
})
})

  4、检测 npm run dev 后,在浏览器地址栏中输入http://localhost:8080/api/goods即可看到数据

  注意:新建goods.json引入时候的路径

  在使用中有个粗心的位置,就是npm run dev的时候总是报错:missing scripts dev,导致项目启动不了。

  考虑到可能是package.json文件里的scripts里面没有dev导致,所以查看,结果却有:

  最后就是粗心导致的问题,原来我是在  cd vueCli 这个目录下去 npm run dev 的,所以肯定会missing scripts dev;改成cd exprice目录下去 npm run dev 就行了。所以一定得细心啊。

使用node中的express解决vue-cli加载不到dev-server.js的问题的更多相关文章

  1. 解决新版本webpack vue-cli生成文件没有dev.server.js问题

    新版本webpack生成的dev.server.js 在webpack.dev.conf.js中 webpack.dev.conf.js const axios = require('axios') ...

  2. 在web.xml中添加配置解决hibernate 懒加载异常

    在web.xml添加如下,注意:在配置在struts2的拦截器之前,只能解决请求时出现的懒加载异常:如果没有请求,还需要lazy属性的添加(比如过滤器) <!-- 配置Spring的用于解决懒加 ...

  3. 在Vue中的load或ready的加载时机

    在Vue中的load或ready的加载时机 1.我们来插入一段代码来分析: Js代码如下 <script type="text/javascript"> var app ...

  4. vue超简单加载字体方法,解决scss难加载字体的问题

    vue超简单加载字体方法,解决scss难加载字体的问题 scss在加载字体方面一直不太好用,需要繁杂的配置才能达到想要的效果,这里说一种非常简单的方法 在App.vue的style标签下引入字体文件后 ...

  5. vue : 无法加载文件 C:\Users\XXX\AppData\Roaming\npm\vue.ps1,因为在此系统上禁止运行脚本

    问题: 使用命令行安装完成vue/cli后,使用vue ui无法创建demo vue : 无法加载文件 C:\Users\yangx\AppData\Roaming\npm\vue.ps1,因为在此系 ...

  6. vue 首次加载缓慢/刷新后加载缓慢 原因及解决方案

    # vue 首次加载缓慢/刷新后加载缓慢 原因及解决方案 最近做项目发现一个问题,页面每次刷新后加载速度都非常慢,20s左右,在开发环境则非常流畅,几乎感觉不到,本文参考望山的各种方案优化 1,关闭打 ...

  7. Vue首页加载过慢 解决方案

    一.什么导致了首页初步加载过慢:app.js文件体积过大 二.解决方法: 1.Vue-router懒加载 vue-router懒加载可以解决首次加载资源过多导致的速度缓慢问题:vue-router支持 ...

  8. Vue动态加载异步组件

    背景: 目前我们项目都是按组件划分的,然后各个组件之间封装成产品.目前都是采用iframe直接嵌套页面.项目中我们还是会碰到一些通用的组件跟业务之间有通信,这种情况下iframe并不是最好的选择,if ...

  9. Android中ViewPager+Fragment取消(禁止)预加载延迟加载(懒加载)问题解决方案

    转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53205878本文出自[DylanAndroid的博客] Android中Vie ...

随机推荐

  1. CSS 绝对居中方案

    .Absolute-Center { margin: auto; position: absolute; top:;;;; }

  2. 176. Second Highest Salary

    Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S ...

  3. 服务器环境从PHP5升级到PHP7

    #安装ppa sudo apt-get install python-software-properties software-properties-common sudo add-apt-repos ...

  4. AC日记——Mato的文件管理 bzoj 3289

    3289 思路: 莫队求区间逆序对个数,树状数组维护: 代码: #include <bits/stdc++.h> using namespace std; #define maxn 500 ...

  5. IllegalStateException: Unable to find a @SpringBootConfiguration

    此处需要改掉包名和类名

  6. Ubuntu18.04 安装Chrome浏览器

    一路copy paste就OK sudo wget http://www.linuxidc.com/files/repo/google-chrome.list -P /etc/apt/sources. ...

  7. vue组件scoped CSS及/deep/深度选择器

    参考链接:https://vue-loader.vuejs.org/zh/guide/scoped-css.html#%E5%AD%90%E7%BB%84%E4%BB%B6%E7%9A%84%E6%A ...

  8. JZYZOJ 1375 双亲数 莫比乌斯反演

    http://172.20.6.3/Problem_Show.asp?id=1375 网上搜推理图. 有一段没有写莫比乌斯反演都快忘了..数学能力--,定理完全不会推,但是这道题整体来说应该是比较好写 ...

  9. Problem D: 统计元音字母数

    #include<stdio.h> int main() { ]; int n,j,k,a,e,i,o,u; a=e=i=o=u=; gets(c); ;c[k]!='\0';k++) { ...

  10. nginx 域名跳转 Nginx跳转自动到带www域名规则配置、nginx多域名向主域名跳转

    nginx 域名跳转 Nginx跳转自动到www域名规则配置,如果设置使 mgcrazy.com域名在用户访问的时候自动跳转到 www.mgcrazy.com呢?在网上找了好多资料都没有一个完整能解决 ...