vue中json-server(模拟数据)
作为前端,在开发的过程,遇到这种调用后端接口调试起来还是很麻烦的,我们要找后端的一个服务器,然后关联起来 ,或者把前端代码放上去,这样都是挺麻烦的,解决的办法就是前端放mock data,主要有两种方式: (1)json-server模拟数据使用json-server这个工具,可以虚构出后端接口对应的数据,然后在项目里发送特定的请求,就可以发请求拿到模拟的数据,首先npm安装...
作为前端,在开发的过程,遇到这种调用后端接口调试起来还是很麻烦的,我们要找后端的一个服务器,然后关联起来 ,或者把前端代码放上去,这样都是挺麻烦的,解决的办法就是前端放mock data,主要有两种方式:
(1)json-server模拟数据
使用json-server这个工具,可以虚构出后端接口对应的数据,然后在项目里发送特定的请求,就可以发请求拿到模拟的数据,首先npm安装
npm install json-server --save
然后在build/webpack.dev.conf.js中进行配置,参考json-server
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
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: true,
hot: true,
host: process.env.HOST || config.dev.host,
port: process.env.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,
}
},
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
}),
]
})
//这里是json-server配置信息(添加这一段进去)
// json-server.js
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiRouter = jsonServer.router('db.json') //数据关联server,db.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://${config.dev.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
配置完成以后,npm run dev 启动,浏览器输入localhost:3000,出现如下图,说明配置成功
那么现在还有一个问题,我们代码的服务端接口是8080,json-server的服务端端口是3000,由于浏览器的同源策略问题,这样请求会存在一个跨域问题,所以这里要做一个服务端代理的配置,配置config/index.js中的proxyTable:
同时更新了config/index.js开发模式dev下几个配置:
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.HOST, 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-
proxyTable:{
'/api/':'http://localhost:3000/'
},
这样就可以在localhost:8080下访问接口了
说明:
autoOpenBrowser:设置启动dev服务器,打开一个新的浏览器选项卡。默认为false,不启动。
useEslint:在webpack中使用eslint-loader。有些人可能只想在他们的IDE中使用eslint,所以可以在这里停用eslint-loader。
showEslintErrorsInOverlay:如果使用eslint-loader,则此选项允许切换浏览器中显示的错误覆盖图中的eslint错误。错误仍然出现在控制台和终端,但不要再打破浏览器的工作流程。notifyOnErrors:将在构建失败时显示操作系统通知。
autoOpenBrowser:设置启动dev服务器,打开一个新的浏览器选项卡。默认为false,不启动。
useEslint:在webpack中使用eslint-loader。有些人可能只想在他们的IDE中使用eslint,所以可以在这里停用eslint-loader。
showEslintErrorsInOverlay:如果使用eslint-loader,则此选项允许切换浏览器中显示的错误覆盖图中的eslint错误。错误仍然出现在控制台和终端,但不要再打破浏览器的工作流程。
notifyOnErrors:将在构建失败时显示操作系统通知。
(2)express启动数据服务
在实际开发中,发现json-server只能用于get请求,不能进行post请求,在网上找的另外一种方法,express既能用于get请求,又能用于post请求,下面说一下express启动服务的配置方法:
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
var express = require('express')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
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: true,
hot: true,
host: process.env.HOST || config.dev.host,
port: process.env.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,
}
},
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
}),
]
})
// json-server.js
//const jsonServer = require('json-server')
//const apiServer = jsonServer.create()
//const apiRouter = jsonServer.router('db.json')
//const middlewares = jsonServer.defaults()
//
//apiServer.use(middlewares)
//apiServer.use('/api',apiRouter)
//apiServer.listen(3000, () => {
// console.log('JSON Server is running')
//})
//express 配置server
var apiServer = express()
var bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require('fs')
apiRouter.route('/:apiName') //接口路径
.all(function (req, res) {
fs.readFile('./db.json', 'utf8', function (err, data) { //读取接口文件
if (err) throw err
var data = JSON.parse(data)
if (data[req.params.apiName]) {
res.json(data[req.params.apiName])
}
else {
res.send('no such api name')
}
})
})
apiServer.use('/api', apiRouter);
apiServer.listen(3000, function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:' + 3000 + '\n')
})
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://${config.dev.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
在浏览器中输入接口地址,如下:
原文:https://blog.csdn.net/benben513624/article/details/78562529
另外一个参考文章:https://blog.csdn.net/obkoro1/article/details/78413389
更多推荐
所有评论(0)