方式一: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': {
// 測試環(huán)境
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
//創(chuàng)建目錄 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"
},
//創(chuàng)建文件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