方式一:http请求-VueResource
npm i vue-resource -D
//main.js
import VueResource from 'vue-resource'
Vue.use(VueResource)
//App.vue
created() {
this.$http.get("http://jsonplaceholder.typicode.com/users")
.then(data=>{
this.UsersInfo=data.body;
console.log(this.UsersInfo);
})
}
方式二:http请求-fetch
fetch("http//:xxx.xxx.com/static/listAll.do",{
method:"post"
}).then(result=>{
console.log(result);
return result.json();
}).then(data=>{
console.log(data);
})
如何解决跨域问题
1、百度vue proxyTable
2、config->index.js 修改
proxyTable: {
'/apis': {
// 测试环境
target: 'http//:xxx.xxx.com/', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite重写的,
}
}
}
3、修改原fetch请求url地址
fetch("/apis/static/listAll.do",{
method:"post"
}).then(result=>{
console.log(result);
return result.json();
}).then(data=>{
console.log(data);
})
方式三:http请求-axios
//main.js
import axios from 'axios'
//axios.defaults.headers.common['token']="";
//axios.defaults.headers.post['Content-type']="application/json";
//axios.defaults.headers.get['Accepts']=''
//axios.defaults.baseUrl=""
Vue.prototype.$axios=axios;
//App.vue
this.$axios.post("/apis/static/listAll.do")
.then(result=>{
console.log(result);
});
后端服务
国外-firebase(谷歌)
国内-野狗(已经关闭)/LeanCloud/Bmob
本地维护数据:json-server
json-server
npm install -g json-server
//创建目录 json-server
npm init -y
npm install json-server --save
//package.json
"scripts": {
"json:server": "json-server --watch db.json",
"json:server:remote":"json-server http://jsonplaceholder.typicode.com/db"
},
//创建文件db.json
npm run json:server
//http://localhost:3000/users
//http://localhost:3000/companies
//db.json
{"users":[
{"name":"jack","phone":"123-456-789","id":1,"age":31,"companyId":1},
{"name":"jack2","phone":"123-456-789","id":2,"age":32,"companyId":2},
{"name":"jack3","phone":"123-456-789","id":3,"age":33,"companyId":3},
{"name":"jack4","phone":"123-456-789","id":4,"age":34,"companyId":3}],
"companies":[
{"id":1,"name":"apple","description":"apple is good"},
{"id":2,"name":"banana","description":"banana is good"},
{"id":3,"name":"melon","description":"melon is good"}]}
#获取所有用户信息
http://localhost:3000/users/
#获取id为1的用户信息
http://localhost:3000/users/1
#获取公司的所有信息
http://localhost:3000/companies
#获取id为2的公司信息
http://localhost:3000/companies/2
#获取名字为apple的公司信息
http://localhost:3000/companies?name=apple
#获取所有公司Id为3的用户
http://localhost:3000/companies/3/users
#根据多个名字获取公司信息
http://localhost:3000/companies?name=apple&name=banana
#获取一页中只有两条数据
http://localhost:3000/companies?_page=1&_limit=1
#asc升序 desc降序
http://localhost:3000/companies?_sort=name&_order=asc
#获取年龄40及以上的
http://localhost:3000/users?age_gte=40
#获取年龄32-40之间的
http://localhost:3000/users?age_gte=32&age_lte=40
#搜索用户信息
http://localhost:3000/users?q=44