0、先建一個json文件:data.json 放在跟目錄下css
一、使用json-server這個工具,能夠虛構出後端接口對應的數據,而後在項目裏發送特定的請求,就能夠發請求拿到模擬的數據,首先npm安裝html
npm install json-server --savevue
二、在build/webpack.dev.conf.js中進行配置webpack
'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 express = require('express') // const app = express() // // var appData = require('../data.json') // var seller = appData.seller // var goods = appData.goods // var ratings = appData.ratings // // var apiRoutes = express.Router() // app.use('/api',apiRoutes) const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT) 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: { 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, }, // 第二步 // before(app) { // app.get('/api/seller', (req,res) => { // res.json({ // errno: 0, // data: seller // })//接口返回json數據,上面配置的數據seller就賦值給data // }), // app.get('/api/goods', (req,res) => { // res.json({ // errno: 0, // data: goods // })//接口返回json數據,上面配置的數據goods就賦值給data // }), // app.get('/api/ratings', (req,res) => { // res.json({ // errno: 0, // data: ratings // })//接口返回json數據,上面配置的數據ratings就賦值給data // }) // } }, 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 }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.dev.assetsSubDirectory, ignore: ['.*'] } ]) ] }) // json-server配置信息 const jsonServer = require('json-server') const apiServer = jsonServer.create() const apiRouter = jsonServer.router('data.json') // 數據關聯server,data.json與index.html同級 const middlewares = jsonServer.defaults() apiServer.use(middlewares) apiServer.use('/api',apiRouter) apiServer.listen(3000, () => { // 監聽端口 console.log('JSON Server is running') }) 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://${devWebpackConfig.devServer.host}:${port}`], }, onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined })) resolve(devWebpackConfig) } }) })
配置完成之後,npm run dev 啓動,瀏覽器輸入localhost:3000,出現以下圖,說明配置成功git
訪問 data.json 數據github
三、代碼的服務端接口是80,json-server的服務端端口是3000,因爲瀏覽器的同源策略問題,這樣請求會存在一個跨域問題,因此這裏要作一個服務端代理的配置,配置build/index.js中的 proxyTable:web
'use strict' // Template version: 1.3.1 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api':{ target: 'http://localhost:3000', pathRewrite: { '^/api': '/' }, changeOrigin: false } }, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 80, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? // If true, your code will be linted during bundling and // linting errors and warnings will be shown in the console. useEslint: true, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, cssSourceMap: true }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report } }
這樣就能夠在localhost:80下訪問接口了ajax
四、在 vue 代碼中能夠發送 ajax 請求express
created: function () { this.$http.get('/api/seller').then((response) => { this.seller = response.data console.log(this.seller) }) },