在前端开发过程中,有后台配合是很必要的。但是如果自己测试开发,或者后台很忙,没时间,那么我们需要自己提供或修改接口。下面提供两种方式
官方文档: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
-
// The Vue build version to load with the `import` command
-
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
-
import Vue
from
'vue'
-
import App
from
'./App'
-
import router
from
'./router'
-
import VueResource
from
'vue-resource'
-
import Layout
from
'./components/layout'
-
-
Vue.use(VueResource);
-
/* eslint-disable no-new */
-
new Vue({
-
el:
'#app',
-
router,
-
template:
'<Layout/>',
-
components: { Layout }
-
})
把vue-resource引入项目以后,就可以在任何组件里面直接用了
-
<template>
-
<div class="index-wrap">
-
<div class="index-left">
-
<div class="index-left-block lastest-news">
-
<h2>最新消息
</h2>
-
<ul>
-
<li v-for="news in newsList">
-
<a :href="news.url" class="new-item">{
{news.title}}
</a>
-
</li>
-
</ul>
-
</div>
-
</div>
-
<div class="index-right">
-
</div>
-
</div>
-
</template>
-
-
<script type="text/ecmascript-6">
-
export
default{
-
created(){
-
this.$http.get(
'api/getNewsList').then(
(res)=>{
//可用post请求,this.$http.post('api/getNewsList',{'userId':123})
-
console.log(res.data);
-
this.newsList=res.data;
-
console.log(
this.newsList);
-
},
(err)=>{
-
console.log(err);
-
});
-
},
-
data(){
-
return {
-
newsList:[],
-
-
}
-
}
-
}
-
</script>
-
-
<style scoped>
-
.index-wrap{
-
width:
1200px;
-
margin:
0 auto;
-
overflow: hidden;
-
background: blue;
-
}
-
.index-left{
-
float: left;
-
width:
300px;
-
text-align: left;
-
background: red;
-
}
-
.index-right {
-
float: left;
-
width:
900px;
-
}
-
-
.index-left-block{
-
margin:
15px;
-
background:
#fff;
-
box-shadow:
0
0
1px
#ddd;
-
}
-
.index-left-block
.hr {
-
margin-bottom:
20px;
-
border-bottom:
1px solid
#ddd;
-
}
-
.index-left-block
h2 {
-
background:
#4fc08d;
-
color:
#fff;
-
padding:
10px
15px;
-
margin-bottom:
20px;
-
}
-
.index-left-block
h3 {
-
padding:
0
15px
5px
15px;
-
font-weight: bold;
-
color:
#222;
-
}
-
.index-left-block
ul {
-
padding:
10px
15px;
-
}
-
.index-left-block
li {
-
padding:
5px;
-
}
-
.hot-tag{
-
background: red;
-
color:
#fff;
-
font-size:
10px;
-
border-radius:
10px;
-
}
-
-
</style>
上面这个就是用vue-resource来进行数据请求的大体流程,作为前端,在开发的过程,遇到这种调用后端接口调试起来还是很麻烦的,我们要找后端的一个服务器,然后关联起来 ,或者把前端代码放上去,这样都是挺麻烦的,解决的办法就是前端放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,由于浏览器的同源策略问题,这样请求会存在一个跨域问题,所以这里要做一个服务端代理的配置,配置build/index.js中的proxyTable:
-
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下访问接口了
(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)
-
}
-
})
-
})
在浏览器中输入接口地址,如下: