In the use of VUE development process, it is unavoidable to go to the local data address request, and the original configuration in dev-server.js
, the new version vue-webpack-template
has been deleted dev-server.js
, instead webpack.dev.conf.js
, so configure local access in the webpack.dev.conf.js
configuration.
Now we're going to use the Express in node to solve the problem of local data requests. Here are three main steps: Install Express and resource, register and use Vue-resource, configure Express, and set up routing rules
1. Install node's Express, and Vue-resource
2, note: Here vue-resource
to install after main.js
registration and use the next
from ' Vue-resource ' vue.use (Vueresource)
3. webpack.dev.conf
Configure Express and set the routing rules
#webpack. Dev.conf.js//first add after const Portfinder = require (' Portfinder ')//NODEJS Development Framework Express for simplified OperationConstExpress = require ('Express')//create an instance of the node. JS Express Development FrameworkConstApp =Express ()//the JSON address of the referencevarAppData = require ('.. /data.json')//JSON one keyvarGoods =Appdata.resultvarApiroutes =Express. Router () App.use ('/api', apiroutes)
(1) Get request configuration
#webpack. Dev.conf.js // in the Devserver option, add the following : before (APP) { app. Get ('/api/someapi', (req, res) = { Res.json ({ // Here is your JSON content } )}
Note: After you modify the configuration file, you need to rerun the command npm run dev
.
(2) Post request configuration. If you want to configure a POST request, you need to configure the folder as follows:
#webpack. Dev.conf.jsapiRoutes.post ('/foods'// Note This will be changed to post Res.json ({ 0, data:foods });}) // inside the component this. $http. Post ('http://localhost:8080/api/foods'). (res) (= { console.log (res)})}
(3) Complete configuration
'Use Strict'ConstUtils = require ('./utils')ConstWebpack = require ('Webpack')ConstConfig = require ('.. /config')ConstMerge = require ('Webpack-merge')ConstPath = require ('Path')ConstBasewebpackconfig = require ('./webpack.base.conf')ConstCopywebpackplugin = require ('Copy-webpack-plugin')ConstHtmlwebpackplugin = require ('Html-webpack-plugin')ConstFriendlyerrorsplugin = require ('Friendly-errors-webpack-plugin')ConstPortfinder = require ('Portfinder')ConstHOST =Process.env.HOSTConstPORT = Process.env.PORT &&Number (Process.env.PORT)//Add Express--startConst EXPRESS = require (' Express ') const APP = Express () var appData = require ('. /goods.json ') var goods = Appdata.goodsvar Apiroutes = Express. Router () app.use ('/api ', apiroutes)//Add Express--endConstDevwebpackconfig =Merge (Basewebpackconfig, {module: {rules:utils.styleLoaders ({sourceMap:config.dev.cssSourceMap, usepostcss: true }) }, //Cheap-module-eval-source-map is faster for developmentDevtool:config.dev.devtool,//These devserver options should be customized In/config/index.jsdevserver: {clientloglevel:'Warning', Historyapifallback: {rewrites: [{ from:/.*/, To:path.posix.join (Config.dev.assetsPublicPath,'index.html')},],}, hot:true, Contentbase:false,//since we use Copywebpackplugin.Compresstrue, 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 Friendlyerrorspluginwatchoptions: {poll:config.dev.poll,},//Add Express--startbefore (APP) {app.get ('/api/goods ', (req, res) = = {Res.json ({code:0, Data:goo (ds})})}//Add Express--end}, plugins: [NewWebpack. Defineplugin ({'process.env': Require ('.. /config/dev.env') }), NewWebpack. Hotmodulereplacementplugin (),NewWebpack. Namedmodulesplugin (),//HMR shows correct file names in console on update. NewWebpack. Noemitonerrorsplugin (),// Https://github.com/ampedandwired/html-webpack-plugin Newhtmlwebpackplugin ({filename:'index.html', Template:'index.html', inject:true }), //Copy custom static assets NewCopywebpackplugin ([{ from: Path.resolve (__dirname,'.. /static'), To:config.dev.assetsSubDirectory, ignore: ['.*'] }]) "}) Module.exports=NewPromise (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 testsProcess.env.PORT =Port//add port to devserver configDevWebpackConfig.devServer.port =Port//ADD FriendlyerrorspluginDevWebpackConfig.plugins.push (NewFriendlyerrorsplugin ({compilationsuccessinfo: {messages: [' Your application isRunning Here:http://${devwebpackconfig.devserver.host}:${port} '],}, OnErrors:config.dev.notifyOnErrors?utils.createnotifiercallback (): undefined})) Resolve (Devwebpackconfig)})})
4, npm run dev
after detection, in the browser address bar input http://localhost:8080/api/goods
can see the data
Note: goods.json
the path of the new introduction
In the use of a careless position, is npm run dev when always error: missing scripts dev, resulting in the project can not start.
Considering that there may be no dev in the scripts in the Package.json file, the results are:
The last is the problem of carelessness, originally I was in the CD VUECLI this directory down npm run dev, so will certainly missing scripts Dev; change to CD Exprice directory go to npm run Dev on the line. So you must be careful.
Use the Express in node to solve the problem that VUE-CLI does not load dev-server.js