使用node中的express解决vue-cli加载不到dev-server.js的问题
在使用vue開發(fā)過程中,難免需要去本地?cái)?shù)據(jù)地址進(jìn)行請(qǐng)求,而原版配置在dev-server.js中,新版vue-webpack-template已經(jīng)刪除dev-server.js,改用webpack.dev.conf.js代替,所以 配置本地訪問在webpack.dev.conf.js里配置即可。
現(xiàn)在我們就來用node里的express來解決本地?cái)?shù)據(jù)請(qǐng)求的問題。主要為下面三步:安裝express和resource、注冊(cè)并使用vue-resource、配置express并設(shè)置路由規(guī)則
1、安裝node的express,和vue-resource
2、注意: 這里安裝vue-resource后需要在main.js注冊(cè)并使用下
import VueResource from 'vue-resource' Vue.use(VueResource)3、在webpack.dev.conf配置express并設(shè)置路由規(guī)則
#webpack.dev.conf.js // 首先在const portfinder = require('portfinder')后添加// nodejs開發(fā)框架express,用來簡化操作 const express = require('express') // 創(chuàng)建node.js的express開發(fā)框架的實(shí)例 const app = express() // 引用的json地址 var appData = require('../data.json') // json某一個(gè)key var goods = appData.resultvar apiRoutes = express.Router() app.use('/api', apiRoutes)(1)get請(qǐng)求配置
#webpack.dev.conf.js // 在devServer選項(xiàng)中添加以下內(nèi)容 before(app) {app.get('/api/someApi', (req, res) => {res.json({// 這里是你的json內(nèi)容 })}) }注意: 修改配置文件完畢后,需要重新運(yùn)行命令npm run dev即可。
(2)post請(qǐng)求配置。如果要配置post請(qǐng)求,需要在該文件夾配置如下:
#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、檢測(cè) npm run dev 后,在瀏覽器地址欄中輸入http://localhost:8080/api/goods即可看到數(shù)據(jù)
注意:新建goods.json引入時(shí)候的路徑
在使用中有個(gè)粗心的位置,就是npm run dev的時(shí)候總是報(bào)錯(cuò):missing scripts dev,導(dǎo)致項(xiàng)目啟動(dòng)不了。
考慮到可能是package.json文件里的scripts里面沒有dev導(dǎo)致,所以查看,結(jié)果卻有:
最后就是粗心導(dǎo)致的問題,原來我是在? cd vueCli 這個(gè)目錄下去 npm run dev 的,所以肯定會(huì)missing scripts dev;改成cd exprice目錄下去 npm run dev 就行了。所以一定得細(xì)心啊。
?
轉(zhuǎn)載于:https://www.cnblogs.com/goloving/p/8695346.html
總結(jié)
以上是生活随笔為你收集整理的使用node中的express解决vue-cli加载不到dev-server.js的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 认识Windows Communicat
- 下一篇: html5倒计时秒杀怎么做,vue 设