GET请求
实例
var result = fetch('/api/1', {
credentials: 'include', //这里是设置跨域请求可以带cookie
headers: { 'Accept': 'application/json, text/plain, */*' }
});
POST请求
实例
// 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
function obj2params(obj) {
var result = '';
var item;
for (item in obj) {
result += '&' + item + '=' + encodeURIComponent(obj[item]);
}
if (result) {
result = result.slice(1);
}
return result;
}
var result = fetch('/api/post', {
method: 'POST', //这里需要设置
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*',
//这里也要设置
'Content-Type': 'application/x-www-form-urlencoded'
},
// 注意 post 时候参数的形式,用&连接
body: obj2params(paramsObj)
});