Recently learning a VUE-CLI project requires data interaction with the background, where local JSON data is used to mimic the background data interaction process. However, there is no dev-server.js file found under the build folder because the new version of Vue-webpack-template The dev-server.js has been removed and replaced by the Webpack.dev.conf.js file, so local access can be configured in Webpack.dev.conf.js.
Compare the old version of the build folder with the new build under build with less dev-server.js and dev-client.js
Older versions
New version
New version configuration webpack.dev.conf.js for local data access, added after const Portfinder = require (' Portfinder ')
Const EXPRESS = require (' Express '= Express () //Create Express Application var appData = require ('. /data.json ')// load Local data file var seller = Appdata.seller// get the corresponding local data var goods = appdata.goodsvar ratings = appdata.ratingsvar apiroutes = Express. Router () //Get an express route instance App.use ('/api ', apiroutes)
Among them, App.use is Express "method of invoking middleware". The so-called middleware (middleware) is a function that handles HTTP requests to accomplish a variety of specific tasks, such as checking whether the user is logged in, analyzing the data, and other tasks that are done before the data needs to be sent to the user eventually. ”。 This is the exact words of Ruan Yi Feng article.
In short, the parameters used in App.use () are mainly functions. But this use, is not a function call, but to enable the meaning. This part of the function is enabled, filtered, and processed when the user makes a request in the browser.
and find it below.devServer,在里面添加
before (APP) { app.get ('/api/seller ', (req, res) = = { Res.json ( {0, data: Seller })// interface returns JSON data, the data configured above is seller assigned to a data request after the call }), App.get ( '/api/goods ', (req, res) = { Res.json ({ 0, data:goods }) }), app.get ('/api/ratings ', (req, res) = { Res.json ({ 0, data:ratings })
Local Data.json data is placed in the root directory with the Index.js peer, re-executing npm run dev, input localhost:8080/api/seller, the results are as follows:
The local data has been requested
Vue simulates background data, requests local data configuration (old version dev-server.js, new version webpack.dev.conf.js)