美文网首页web前端学习vuevue
Vue2.0史上最全入坑教程(续)—dev-server失踪问题

Vue2.0史上最全入坑教程(续)—dev-server失踪问题

作者: 诺奕 | 来源:发表于2017-11-26 19:21 被阅读7762次

一、前言

vue-cli(版本更新),由原来的2.8.1升级为2.9.1。主要改变是原来在build文件夹下的dev-server.js删掉了,增加了webpack.dev.conf.js。导致原来通过express方式引入的数据找不到。本文将针对此问题,提供两种结局方案。

二、方案A— 使用node中的express

我们知道在2.9.1的版本中没有express

  • 注意: 这里安装vue-resource后需要在main.js注册并使用下
import VueResource from 'vue-resource'
Vue.use(VueResource)
  • webpack.dev.conf配置express并设置路由规则
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
/* datura_lj 增加express 20171126 */
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: true,
    hot: true,
    compress: true,
    host: process.env.HOST || config.dev.host,
    port: process.env.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,
    },
    /* datura_lj 增加express 20171126 */
    before(app) {
      app.get('/api/goods', (req, res) => {
        res.json({
          code: 0,
          data: goods
        })
      })
    } 
    /* datura_lj 增加路由规则 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
    }),
  ]
})

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://${config.dev.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})
  • 检测 npm run dev后,在浏览器地址栏中输入http://127.0.0.1:8080/api/goods即可看到数据
  • 注意 新建goods.json引入时候的路径

二、方案B— 使用json-server,启动一个server

  • 新建server文件夹并配置相关信息
|--server
  |--package.json
  |--static
    |--config.js
    |--db.json
    |--server.js
1. package.json
{
  "name": "json-server-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "server": "cd static && nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "json-server": "^0.9.6",
    "nodemon": "^1.11.0"
  }
}

2. config.js
module.exports = {
  SERVER:"127.0.0.1",  
  PORT: 9527,
  DB_FILE:"db.json"
};
3. db.json

数据文件

4. server.js
const path = require('path');
const config = require('./config');
const jsonServer = require('json-server');
const ip = config.SERVER;
const port = config.PORT;
const db_file = config.DB_FILE;
const server = jsonServer.create();
const router = jsonServer.router(path.join(__dirname, config.DB_FILE));
const middlewares = jsonServer.defaults();
server.use(jsonServer.bodyParser);
server.use(middlewares);
server.use((req, res, next) => {
  res.header('X-Hello', 'datura_lj');
  next();
})
router.render = (req, res) => {
  res.jsonp({
    code: 0,
    body: res.locals.data
  })
}
server.use("/api", router);
server.use(router);
server.listen({
  host: ip,
  port: port
}, function () {
  console.log(JSON.stringify(jsonServer));
  console.log(`JSON Server is running in http://${ip}:${port}`);
});

  • 检测server文件下执行npm run server后,在浏览器地址栏中输入http://127.0.0.1:9527/goods即可看到数据

三、在vue组件中,调取数据

 created () {
    /*
    * 方式一
    * 使用node中的express
    */
    /*this.$http.get('/api/goods').then((data) => {
      if(data.body.code == 0){
        this.imgArr = data.body.data;
        console.log(this.imgArr)
      }
    })*/
    /*
    * 方式二
    * 使用json-server方式
    */
    this.$http.get('http://127.0.0.1:9527/goods').then((data) => {
      console.log(data.body)
      if(data.body.code == 0){
        this.imgArr = data.body.body;
        console.log(this.imgArr)
      }
    })
  }

四、效果展示

五、其他

本文只是针对数据问题解决,具体组件渲染以及路由规则,还请继续看以前文章。
对以入门的朋友请看提高版本

相关文章

网友评论

  • be2753df0b2d:http://localhost:8080/#/api/goods为什么我跑出来之后,页面上显示的是一张vue的图片呢
    3eb85321c40e:把井号删掉就可以了
  • 934332d108a0:你好 我的main.js的目录是 src/main.js
    修改的内容是
    // The Vue build version to load with the `import` command
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import VueResource from 'vue-resource'
    Vue.use(VueResource)

    Vue.config.productionTip = false
    /* eslint-disable no-new */
    new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>'
    })

    但是我运行 rpm run dev的时候 会报错误如下

    $ npm run dev

    > y@1.0.0 dev D:\vue\exprice
    > webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

    94% asset optimization ERROR Failed to compile with 2 errors17:40:48

    These relative modules were not found:

    * ../App in ./src/main.js
    * ../router in ./src/main.js WAIT Compiling...17:41:08

    94% asset optimization ERROR Failed to compile with 2 errors17:41:09

    These relative modules were not found:

    * ./App in ./src/main.js
    * ./router in ./src/main.js
  • 看到这朵小fa了么:我用了方案B,在创建根文件夹server后需要安装一下nodemon 、json-server ,cd到server文件夹下运行会报错cannt find json-server,在https://github.com/typicode/json-server/issues/454 找到这里路径有一些问题,需要配置,或者直接npm link json-server会在server文件夹下生成一个node_modules文件夹,这时再run server 就可以了,感谢楼主的分享,比心
    I_I_I:想问一下 我用了npm link json-server之后,再run server会报错[nodemon] app crashed - waiting for file changes before starting。
  • a06968eb7b75:在vue组件中调取数据,是在哪个组件里调呀
    b6faaaf2acfa:home.vue
    注意:
    this.$http.get('http://127.0.0.1:9527/goods').then((data) => {
    console.log(data.body)
    if(data.body.code == 0){
    this.imgArr = data.body.body;
    console.log(this.imgArr)
    要改成:this.items = data.body.body
  • a06968eb7b75:想要这个跑起来,还需要添加东西吗
  • a06968eb7b75:为什么我完全按照你的来弄得,没有注释,没有赋值代码,为什么跑不起来呀
  • a06968eb7b75:我刚开始学习vue,这个是直接就可以运行起来吗。问什么我完全按照你的来弄得,跑不起来呀
  • L_c017:作者大大,为什么方案A中的代码加到入口文件(那个js)文件就不行呢?报in ./node_modules/express/lib/view.js
    Critical dependency: the request of a dependency is an expression这个错误。
    为什么要加在web.config.js中呢?
  • 95362357deda:困扰了2天的测试接口数据问题终于解决了,网上很多博客的方法都是过去的版本,搞得焦头烂额,感谢分享!:kissing_heart:
    诺奕:@17岁歌手想当程序员 解决就好,继续加油
  • 隐号骑士:想问一下楼主方案A中的before()方法是什么定义?
    还有,在里面定义app.post()好像没有用诶
  • ef8ff161cc62:请问是要在哪个vue组件中调取数据呢?
  • ef04caa010a5:楼主大大我在采用第一种方法的时候在控制台中console出来的undefined,json文件放在index同级目录了 路径应该不会错吧 然后访问到的数据就只是{"code":0}这个
  • 欧石南:想问下使用方案A的方法时,npm run dev老是有error是什么原因
    npm-debug中打印的日志:
    error Windows_NT 6.1.7601
    18 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
    19 error node v6.9.1
    20 error npm v3.10.8
    21 error code ELIFECYCLE
    22 error shopcar@1.0.0 dev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js`
    22 error Exit status 1
    23 error Failed at the shopcar@1.0.0 dev script 'webpack-dev-server --inline --progress --config build/webpack.dev.conf.js'.
    23 error Make sure you have the latest version of node.js and npm installed.
    23 error If you do, this is most likely a problem with the shopcar package,
    23 error not with npm itself.
    23 error Tell the author that this fails on your system:
    23 error webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
    23 error You can get information on how to open an issue for this project with:
    23 error npm bugs shopcar
    23 error Or if that isn't available, you can get their info via:
    23 error npm owner ls shopcar
    23 error There is likely additional logging output above.
    24 verbose exit [ 1, true ]
    欧石南:@datura_lj 试了,还是不行
    诺奕:@欧石南 删除依赖包 cnpm Install 重新安装

本文标题:Vue2.0史上最全入坑教程(续)—dev-server失踪问题

本文链接:https://www.haomeiwen.com/subject/hiqlbxtx.html