module.exports = {
/**
* GET请求
* @param {请求路径} api_url
* @param {参数列表} param
* @param {成功回调} successBack
* @param {失败回调} failureBack
*/
GET:(api_url, param, successBack, failureBack)=>{
// 1. 参数拼接总串, 拼接操作符, 索引
var allParamStr = ' ', flag = '?', index = 0;
// 2. 把json对象转成字符串
var jsonStr = JSON.stringify(param);
if (jsonStr !== undefine || jsonStr !== '{}') { // 过滤
for (key in param){
if (index > 0) {
flag = '&'
}
allParamStr += mark + flag + '=' + param[key];
index++;
}
}
// 3.拼接参数
api_url += totalParamStr;
fetch(api_url)
.then((response)=>response.json())
.then((responseJson)=>{ // 成功回调
successBack(responseJson);
})
.catch((error)=>{ // 失败回调
failureBack(error);
})
}
};
fetch('http://192.168.0.138:3000/userlogin/', {
method: 'POST', // 请求方式
headers: { // 请求头
'Accept': 'application/json', // 接收的是json格式数据
'Content-Type': 'application/json',
},
body: JSON.stringify({ // 把json对象转成字符串
firstParam: 'yourValue', // 要传递的参数
secondParam: 'yourOtherValue',
})
})
module.exports = {
Post(){
fetch('http://192.168.0.138:3000/userlogin',{
method:'POST',
headers:{
'Content-Type':'application/json' // 不能写错
},
body:JSON.stringify({ // 把json对象转成字符串
name: 'xzh',
pwd: '12306',
})
})
.then((response)=>response.json())
.then((json)=>{
console.log(json)
})
.catch((error)=>{
console.log(error)
})
}
}
module.exports = {
/**
* POST请求
* @param {请求路径} api_url
* @param {参数列表} param
* @param {成功回调} success
* @param {失败回调} failure
*/
POST(api_url, param, success, failure) {
fetch(api_url,{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(param)
})
.then((response)=>response.json())
.then((responseJson)=>{
success(responseJson);
})
.catch((error)=>{
failure(error);
})
}
}