GET 请求
//请求的网址
var url = "http://127.0.0.1:7777/list";
//发起get请求
var promise = fetch(url).then(function(response) {
//response.status表示响应的http状态码
if(response.status === 200){
//json是返回的response提供的一个方法,会把返回的json字符串反序列化成对象,也被包装成一个Promise了
return response.json();
}else{
return {}
}
});
promise = promise.then(function(data){
//响应的内容
console.log(data);
}).catch(function(err){
console.log(err);
})
post请求:
fetch("http://127.0.0.1:7777/postContent", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
mode: "cors",
body: JSON.stringify({
content: "留言内容"
})
}).then(function(res) {
if (res.status === 200) {
return res.json()
} else {
return Promise.reject(res.json())
}
}).then(function(data) {
console.log(data);
}).catch(function(err) {
console.log(err);
});