使用node中的express解决vue-cli加载不到dev-server.js的问题
在使用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.resultvar 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: 0,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 --endconst 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-pluginnew HtmlWebpackPlugin({filename: 'index.html',template: 'index.html',inject: true}),// copy custom static assetsnew CopyWebpackPlugin([{from: path.resolve(__dirname, '../static'),to: config.dev.assetsSubDirectory,ignore: ['.*']}])] })module.exports = new Promise((resolve, reject) => {portfinder.basePort = process.env.PORT || config.dev.portportfinder.getPort((err, port) => {if (err) {reject(err)} else {// publish the new Port, necessary for e2e testsprocess.env.PORT = port// add port to devServer configdevWebpackConfig.devServer.port = port// Add FriendlyErrorsPlugindevWebpackConfig.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 就行了。所以一定得細心啊。
?
轉載于:https://www.cnblogs.com/goloving/p/8695346.html
總結
以上是生活随笔為你收集整理的使用node中的express解决vue-cli加载不到dev-server.js的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 认识Windows Communicat
- 下一篇: Vue-Router + Vuex 实现