fetch使用案例
const get_html = async (url) => {
return await fetch(url, {
method: "get",
// mode: "no-cors",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
// "X-Requested-With": "XMLHttpRequest",
},
// body: new FormData(document.getElementById("comment-form")),
//或者
//body: JSON.stringify({
// email: 'huang@163.com'
// name: 'jim'
//})
})
.then((response) => {
const type = "json";
//response 这个对象并不与 servlet中的一样
if (type === "json") {
return response.text(); //返回一个text的resolve的promise对象
} else {
return response.json(); //返回一个json的resolve的promise对象
}
})
.then((data) => {
console.log("返回的数据!");
// console.log("返回的数据!", data);
return data;
//可以设置返回一个 promise对象 的状态
})
.catch((err) => {
console.log("请求异常!");
});
};
export default get_html;
或者直接写
export default function get_html(url) {
fetch("www.baidu.com", {
method: "GET",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
.then((response) => {
console.log("成功了", response.text());
// return response.text();
})
// .then((res) => res.text())
.then((body) => {
console.log(body);
})
.catch((error) => {
console.error(error);
console.log("失败了", error);
});
}