安裝
使用 npm 安裝 whatwg-fetch 和 es6-promise
npm install whatwg-fetch --save
npm install es6-promise --save
示例
import 'whatwg-fetch'
import 'es6-promise'
//get請(qǐng)求
export function getDate() {
var result = fetch('/api/1',{
methods: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*'
}
})
result.then((res) => {
return res.text()
}).then((text) => {
console.log(text) // 打印出來(lái)的為一個(gè)text數(shù)據(jù)
})
var result2 = fetch('/api/2',{
methods: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*'
}
})
result.then((res) => {
return res.json()
}).then((json) => {
console.log(json)// 打印出來(lái)的為一個(gè)json格式的數(shù)據(jù)
})
}
//post 請(qǐng)求
//對(duì)象轉(zhuǎn)換成字符串形式 item=1&item2=2
function paramesObj(obj) {
var str = '',item;
for (item in obj) {
str += '&' + item + '=' + encodeURIComponent(obj[item])
}
if (str) {
str = str.slice(1)
}
return str
}
export function postDate() {
var result = fetch('/api/1',{
methods: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
// 注意 post 時(shí)候參數(shù)的形式
body: "a=1&b=100"
})
result.then((res) => {
return res.json()
}).then((json) => {
console.log(json)
})
}