Vue mock数据,模拟后台接口

在前端开发过程中,有后台配合是很必要的。但是如果自己测试开发,或者后台很忙,没时间,那么我们需要自己提供或修改接口。下面提供两种方式


官方文档:https://github.com/nuysoft/Mock/wiki/Getting-Started

关于mockjs,官网描述的是

1.前后端分离

2.不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。

3.数据类型丰富

4.通过随机数据,模拟各种场景。

等等优点。

总结起来就是在后端接口没有开发完成之前,前端可以用已有的接口文档,在真实的请求上拦截ajax,并根据mockjs的mock数据的规则,模拟真实接口返回的数据,并将随机的模拟数据返回参与相应的数据交互处理,这样真正实现了前后台的分离开发。

与以往的自己模拟的假数据不同,mockjs可以带给我们的是:在后台接口未开发完成之前模拟数据,并返回,完成前台的交互;在后台数据完成之后,你所做的只是去掉mockjs:停止拦截真实的ajax,仅此而已。


一、mock文件

1、安装,开发环境

npm i mockjs -D

2、在src目录下新建mock目录,结构如下:

在这里插入图片描述

mock.js里


import Mock from "mockjs";

//mock数据
var result=Mock.mock({
    
    
  code: 200,
  msg: "操作成功",
  data: {
    
    
    current_page: 1,
    last_page: 18,
    total: 178,
    "list|10": [
      {
    
    
        id: "@id",  //模拟id
        "price|100-200.1-2": 100, //模拟小数,在计算机中也称浮点数
        "has_buy|1": [0, 1], //模拟状态值,0,1,2,
        title: "@ctitle",  //模拟中文标题
        address: "@county(true)",  //模拟省市县
        "teachers_list|1": [
          {
    
    
            course_basis_id: "@id",
            id: "@id",
            teacher_avatar: "@image('150x120', '#ff0000', '1909A')",  //模拟图片
            teacher_name: "@cname"  //模拟中文姓名
          }
        ]
      }
    ]
  }
});
export default result;

创建mock的入口文件index.js,并配置请求的接口地址,提交方式,返回的假数据

index.js

import Mock from 'mockjs'
//导入的模拟数据
import analogData from "./mock";

/**
 * Mock.mock( rurl, rtype, template )
 * rurl:请求的接口地址
 * rtype:提交方式
 * template:返回数据
 */ 

Mock.mock("http://lvsige/mockData", "get", analogData);


3、在main.js入口文件中引入mock数据,不需要时,则注释掉。

//引入mock数据
import './mock'

4、在vue模板访问

 mounted() {
    
    
        axios.get('http://lvsige/mockData').then(res=>{
    
    
                console.log(res)
        })
          
      },

5.在浏览器里访问

在这里插入图片描述

二、第三方接口eolinker

1、官网接口地址: https://lvsige.w.eolinker.com/#/
需登录,没注册过的小伙伴,注册一个账号吧。

2、注册好后有一个默认接口,当然我们要做自己的项目。
3、新建项目
在这里插入图片描述
4、添加接口
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
6、使用接口
在这里插入图片描述
7、前端项目中,后台url地址,有开发版,测试版,产线版等多个版本,建议大家统一管理,访问时,做url拼接

但是本人还没有成功的返回多条数据,只是拿到了自己模拟的数据
在寻找方案的路上ing

会回来更新!!

三、模拟后台……

放着备用!

vue实现ajax获取后台数据是通过vue-resource,首先通过npm安装vue-resource

npm install vue-resource --save
安装完成以后,把vue-resource引入到main.js文件中

src/main.js


 
  
  
  1. // The Vue build version to load with the `import` command
  2. // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
  3. import Vue from 'vue'
  4. import App from './App'
  5. import router from './router'
  6. import VueResource from 'vue-resource'
  7. import Layout from './components/layout'
  8. Vue.use(VueResource);
  9. /* eslint-disable no-new */
  10. new Vue({
  11. el: '#app',
  12. router,
  13. template: '<Layout/>',
  14. components: { Layout }
  15. })
把vue-resource引入项目以后,就可以在任何组件里面直接用了


 
  
  
  1. <template>
  2. <div class="index-wrap">
  3. <div class="index-left">
  4. <div class="index-left-block lastest-news">
  5. <h2>最新消息 </h2>
  6. <ul>
  7. <li v-for="news in newsList">
  8. <a :href="news.url" class="new-item">{ {news.title}} </a>
  9. </li>
  10. </ul>
  11. </div>
  12. </div>
  13. <div class="index-right">
  14. </div>
  15. </div>
  16. </template>
  17. <script type="text/ecmascript-6">
  18. export default{
  19. created(){
  20. this.$http.get( 'api/getNewsList').then( (res)=>{ //可用post请求,this.$http.post('api/getNewsList',{'userId':123})
  21. console.log(res.data);
  22. this.newsList=res.data;
  23. console.log( this.newsList);
  24. }, (err)=>{
  25. console.log(err);
  26. });
  27. },
  28. data(){
  29. return {
  30. newsList:[],
  31. }
  32. }
  33. }
  34. </script>
  35. <style scoped>
  36. .index-wrap{
  37. width: 1200px;
  38. margin: 0 auto;
  39. overflow: hidden;
  40. background: blue;
  41. }
  42. .index-left{
  43. float: left;
  44. width: 300px;
  45. text-align: left;
  46. background: red;
  47. }
  48. .index-right {
  49. float: left;
  50. width: 900px;
  51. }
  52. .index-left-block{
  53. margin: 15px;
  54. background: #fff;
  55. box-shadow: 0 0 1px #ddd;
  56. }
  57. .index-left-block .hr {
  58. margin-bottom: 20px;
  59. border-bottom: 1px solid #ddd;
  60. }
  61. .index-left-block h2 {
  62. background: #4fc08d;
  63. color: #fff;
  64. padding: 10px 15px;
  65. margin-bottom: 20px;
  66. }
  67. .index-left-block h3 {
  68. padding: 0 15px 5px 15px;
  69. font-weight: bold;
  70. color: #222;
  71. }
  72. .index-left-block ul {
  73. padding: 10px 15px;
  74. }
  75. .index-left-block li {
  76. padding: 5px;
  77. }
  78. .hot-tag{
  79. background: red;
  80. color: #fff;
  81. font-size: 10px;
  82. border-radius: 10px;
  83. }
  84. </style>
上面这个就是用vue-resource来进行数据请求的大体流程,作为前端,在开发的过程,遇到这种调用后端接口调试起来还是很麻烦的,我们要找后端的一个服务器,然后关联起来 ,或者把前端代码放上去,这样都是挺麻烦的,解决的办法就是前端放mock data,主要有两种方式:

(1)json-server模拟数据

使用json-server这个工具,可以虚构出后端接口对应的数据,然后在项目里发送特定的请求,就可以发请求拿到模拟的数据,首先npm安装

npm install json-server --save
然后在build/webpack.dev.conf.js中进行配置,参考 json-server


 
  
  
  1. 'use strict'
  2. const utils = require( './utils')
  3. const webpack = require( 'webpack')
  4. const config = require( '../config')
  5. const merge = require( 'webpack-merge')
  6. const baseWebpackConfig = require( './webpack.base.conf')
  7. const HtmlWebpackPlugin = require( 'html-webpack-plugin')
  8. const FriendlyErrorsPlugin = require( 'friendly-errors-webpack-plugin')
  9. const portfinder = require( 'portfinder')
  10. const devWebpackConfig = merge(baseWebpackConfig, {
  11. module: {
  12. rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  13. },
  14. // cheap-module-eval-source-map is faster for development
  15. devtool: config.dev.devtool,
  16. // these devServer options should be customized in /config/index.js
  17. devServer: {
  18. clientLogLevel: 'warning',
  19. historyApiFallback: true,
  20. hot: true,
  21. host: process.env.HOST || config.dev.host,
  22. port: process.env.PORT || config.dev.port,
  23. open: config.dev.autoOpenBrowser,
  24. overlay: config.dev.errorOverlay ? {
  25. warnings: false,
  26. errors: true,
  27. } : false,
  28. publicPath: config.dev.assetsPublicPath,
  29. proxy: config.dev.proxyTable,
  30. quiet: true, // necessary for FriendlyErrorsPlugin
  31. watchOptions: {
  32. poll: config.dev.poll,
  33. }
  34. },
  35. plugins: [
  36. new webpack.DefinePlugin({
  37. 'process.env': require( '../config/dev.env')
  38. }),
  39. new webpack.HotModuleReplacementPlugin(),
  40. new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
  41. new webpack.NoEmitOnErrorsPlugin(),
  42. // https://github.com/ampedandwired/html-webpack-plugin
  43. new HtmlWebpackPlugin({
  44. filename: 'index.html',
  45. template: 'index.html',
  46. inject: true
  47. }),
  48. ]
  49. })
  50. //这里是json-server配置信息
  51. // json-server.js
  52. const jsonServer = require( 'json-server')
  53. const apiServer = jsonServer.create()
  54. const apiRouter = jsonServer.router( 'db.json') //数据关联server,db.json与index.html同级
  55. const middlewares = jsonServer.defaults()
  56. apiServer.use(middlewares)
  57. apiServer.use( '/api',apiRouter)
  58. apiServer.listen( 3000, () => { //监听端口
  59. console.log( 'JSON Server is running')
  60. })
  61. module.exports = new Promise( (resolve, reject) => {
  62. portfinder.basePort = process.env.PORT || config.dev.port
  63. portfinder.getPort( (err, port) => {
  64. if (err) {
  65. reject(err)
  66. } else {
  67. // publish the new Port, necessary for e2e tests
  68. process.env.PORT = port
  69. // add port to devServer config
  70. devWebpackConfig.devServer.port = port
  71. // Add FriendlyErrorsPlugin
  72. devWebpackConfig.plugins.push( new FriendlyErrorsPlugin({
  73. compilationSuccessInfo: {
  74. messages: [ `Your application is running here: http://${config.dev.host}:${port}`],
  75. },
  76. onErrors: config.dev.notifyOnErrors
  77. ? utils.createNotifierCallback()
  78. : undefined
  79. }))
  80. resolve(devWebpackConfig)
  81. }
  82. })
  83. })
配置完成以后,npm run dev 启动,浏览器输入localhost:3000,出现如下图,说明配置成功


那么现在还有一个问题,我们代码的服务端接口是8080,json-server的服务端端口是3000,由于浏览器的同源策略问题,这样请求会存在一个跨域问题,所以这里要做一个服务端代理的配置,配置build/index.js中的proxyTable:


 
  
  
  1. host: 'localhost', // can be overwritten by process.env.HOST
  2. port: 8080, // can be overwritten by process.env.HOST, if port is in use, a free one will be determined
  3. autoOpenBrowser: false,
  4. errorOverlay: true,
  5. notifyOnErrors: true,
  6. poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
  7. proxyTable:{
  8. '/api/': 'http://localhost:3000/'
  9. },
这样就可以在localhost:8080下访问接口了


(2)express启动数据服务

在实际开发中,发现json-server只能用于get请求,不能进行post请求,在网上找的另外一种方法,express既能用于get请求,又能用于post请求,下面说一下express启动服务的配置方法:


 
  
  
  1. 'use strict'
  2. const utils = require( './utils')
  3. const webpack = require( 'webpack')
  4. var express = require( 'express')
  5. const config = require( '../config')
  6. const merge = require( 'webpack-merge')
  7. const baseWebpackConfig = require( './webpack.base.conf')
  8. const HtmlWebpackPlugin = require( 'html-webpack-plugin')
  9. const FriendlyErrorsPlugin = require( 'friendly-errors-webpack-plugin')
  10. const portfinder = require( 'portfinder')
  11. const devWebpackConfig = merge(baseWebpackConfig, {
  12. module: {
  13. rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  14. },
  15. // cheap-module-eval-source-map is faster for development
  16. devtool: config.dev.devtool,
  17. // these devServer options should be customized in /config/index.js
  18. devServer: {
  19. clientLogLevel: 'warning',
  20. historyApiFallback: true,
  21. hot: true,
  22. host: process.env.HOST || config.dev.host,
  23. port: process.env.PORT || config.dev.port,
  24. open: config.dev.autoOpenBrowser,
  25. overlay: config.dev.errorOverlay ? {
  26. warnings: false,
  27. errors: true,
  28. } : false,
  29. publicPath: config.dev.assetsPublicPath,
  30. proxy: config.dev.proxyTable,
  31. quiet: true, // necessary for FriendlyErrorsPlugin
  32. watchOptions: {
  33. poll: config.dev.poll,
  34. }
  35. },
  36. plugins: [
  37. new webpack.DefinePlugin({
  38. 'process.env': require( '../config/dev.env')
  39. }),
  40. new webpack.HotModuleReplacementPlugin(),
  41. new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
  42. new webpack.NoEmitOnErrorsPlugin(),
  43. // https://github.com/ampedandwired/html-webpack-plugin
  44. new HtmlWebpackPlugin({
  45. filename: 'index.html',
  46. template: 'index.html',
  47. inject: true
  48. }),
  49. ]
  50. })
  51. // json-server.js
  52. //const jsonServer = require('json-server')
  53. //const apiServer = jsonServer.create()
  54. //const apiRouter = jsonServer.router('db.json')
  55. //const middlewares = jsonServer.defaults()
  56. //
  57. //apiServer.use(middlewares)
  58. //apiServer.use('/api',apiRouter)
  59. //apiServer.listen(3000, () => {
  60. // console.log('JSON Server is running')
  61. //})
  62. //express 配置server
  63. var apiServer = express()
  64. var bodyParser = require( 'body-parser')
  65. apiServer.use(bodyParser.urlencoded({ extended: true }))
  66. apiServer.use(bodyParser.json())
  67. var apiRouter = express.Router()
  68. var fs = require( 'fs')
  69. apiRouter.route( '/:apiName') //接口路径
  70. .all( function (req, res) {
  71. fs.readFile( './db.json', 'utf8', function (err, data) { //读取接口文件
  72. if (err) throw err
  73. var data = JSON.parse(data)
  74. if (data[req.params.apiName]) {
  75. res.json(data[req.params.apiName])
  76. }
  77. else {
  78. res.send( 'no such api name')
  79. }
  80. })
  81. })
  82. apiServer.use( '/api', apiRouter);
  83. apiServer.listen( 3000, function (err) {
  84. if (err) {
  85. console.log(err)
  86. return
  87. }
  88. console.log( 'Listening at http://localhost:' + 3000 + '\n')
  89. })
  90. module.exports = new Promise( (resolve, reject) => {
  91. portfinder.basePort = process.env.PORT || config.dev.port
  92. portfinder.getPort( (err, port) => {
  93. if (err) {
  94. reject(err)
  95. } else {
  96. // publish the new Port, necessary for e2e tests
  97. process.env.PORT = port
  98. // add port to devServer config
  99. devWebpackConfig.devServer.port = port
  100. // Add FriendlyErrorsPlugin
  101. devWebpackConfig.plugins.push( new FriendlyErrorsPlugin({
  102. compilationSuccessInfo: {
  103. messages: [ `Your application is running here: http://${config.dev.host}:${port}`],
  104. },
  105. onErrors: config.dev.notifyOnErrors
  106. ? utils.createNotifierCallback()
  107. : undefined
  108. }))
  109. resolve(devWebpackConfig)
  110. }
  111. })
  112. })
在浏览器中输入接口地址,如下:





猜你喜欢

转载自blog.csdn.net/weixin_46034375/article/details/108540370