json-server
-
建立模拟数据:在src同级目录下创建文件:db.json
-
首先先下载包
npm install json-server -g
-
打开集成终端,设置端口,这个端口是你脚手架的端口号,方便代理
json-server db.json --port 8080
-
打开package.json文件 然后在scripts中配置一个mock,这个端口号是访问你虚拟数据的端口号:
"mock": "json-server db.json --port 3003" "scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", "build": "node build/build.js", "mock": "json-server db.json --port 3003"
},
- 执行 npm run dev
也可以直接访问 http://localhost:3003/
发现 http://localhost:3003/
http://localhost:8080/是一样
6. 书写测试代码,你可以直接但APP.vue上测试,或者删掉重新配置,记得在main.js中y引入文件并直接渲染 render:(h) =>h(文件名)
这时候要才用多线程,也就是你要多开个终端,先关掉之前的终端,因为刚刚在json-server db.json --port 8080,8080端口被使用了,为了防止端口占用,全部关掉。然后重新一个启动json-server,一个启动项目npm run dev
<template>
<div id="app">
{{login}}
</div>
</template>
<script>
export default {
created: function () {
this.$http.get('http://localhost:8080/login')
.then((res) => {
this.login = res.data
}, (err) => {
console.log(err)
})
},
data () {
return {
login:[]
}
}
}
</script>
代理服务器
简单理解就是当你访问/api时你会映射到你的虚拟数据http://localhost:3003,
就是/api是http://localhost:3003的代言人!!!!
- 设置config/index.js 的proxyTable
proxyTable: {
'/api/': {
target: 'http://localhost:3003', //将http://localhost:3003映射到/api
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '', // 因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/'
}
}
},
http://localhost:8080/api将会映射访问到http://localhost:3003页面,起到一个代理作用
- 修改请求的url地址
export default {
created: function () {
this.$http.get('/api/login')
.then((res) => {
this.login = res.data
}, (err) => {
console.log(err)
})
},
data () {
return {
login:[]
}
}
}
</script>
- 重新启动 npm run dev
- 请求对应数据也要加/api/
eg:
axios
-
首先下包
npm install axios
-
在main.js中引入
var axios = require('axios');
-
发出请求
axios.get('/api/dataInData')
.then(function(response){
console.log(response);
}).catch(function(response){
console.log(response);
});