fetch发送get请求

JavaScript 可以将网络请求发送到服务器,并在需要时加载新信息。对于来自 JavaScript 的网络请求,有一个总称术语 “AJAX”(Asynchronous JavaScript And XML 的简称)。有很多方式可以向服务器发送网络请求,并从服务器获取信息。fetch是其中之一,旧版本的浏览器不支持它(可以 polyfill),但是它在现代浏览器中的支持情况很好。
我们来看一看它的基本语法

let url="test.html";
let te = fetch(url);
console.log(te);

fetch 请求设置responseType_javascript

参数1:要访问的url,
其他参数:包括method、header等。method没有传入参数则默认为get方式。
它返回一个promise对象,因此我们可以使用promise的方法获取返回的结果

te.then((resolve)=>{
console.log(resolve);
});

fetch 请求设置responseType_数据_02


由此可见返回的结果是一个response对象,由此我们可以通过ok属性来判断是否响应成功该步骤类似于ajax中的判断xhr.readyStateh和xhr.status这个步骤。

//ok属性的是一个布尔类型的值
te.then((resolve)=>{
if(resolve.ok){
console.log(resolve);
}
});

接下来就要接受相应数据,和ajax类似,fetch返回的response对象通过text方法获取响应数据

te.then((resolve)=>{
if(resolve.ok){
console.log(resolve.text());
}
});

fetch 请求设置responseType_数据_03


根据结果,它返回一个promise对象,我们仍可以使用promise的方法获取

te.then((resolve)=>{
if(resolve.ok){
console.log(resolve.text().then((resolve)=>{console.log(resolve)}));
}
});

fetch 请求设置responseType_数据_04

由此我们就接受到了相应的数据,接下来我们将上面的代码汇总

let url = "test.html";
    let te = fetch(url);
    te.then((resolve) => {
    if(resolve.ok){
     return resolve.text()
    }
    }).then((resolve) => {
            console.log(resolve);
      });
   // 也可以写成这样
 //fetch(url).then((resolve) => resolve.text()).then((resolve) => console.log(resolve));

对于JSON格式的数据还可以使用json方法进行获取

let url="https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits";
fetch(url).then((resolve) => {
if(resolve.ok){
return resolve.json();
}
}).then((resolve) => console.log(resolve));

fetch 请求设置responseType_javascript_05


由此我们就获得了响应的数据,以上就是一个使用fetch发送get请求的过程。

fetch发送post请求

该过程与发送get请求步骤基本一致,主要在第一步中要设置请求方式为post,并且要设置请求头,并传入要提交的参数

fetch("https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
",{
method:"POST",
headers:{
'Content-Type': 'application/json;charset=utf-8'
},
body:{
userName:"Liyu"
}
}).then((resolve=>{
if(resolve.ok){
	return resolve.json();
}
)).then();

请注意,如果请求的 body 是字符串,则 Content-Type 会默认设置为 text/plain;charset=UTF-8。
但是,当我们要发送 JSON 时,我们会使用 headers 选项来发送 application/json,这是 JSON 编码的数据的正确的 Content-Type。
如果想要传递形如,"name=Li&age=10"的参数,headers的Content-Type需要设置为application/x-www-form-urlencoded
如果存在跨域问题,需要设置mode 为 cors 或 no-cros

总结

  • fetch发送请求步骤
  1. 调用fetch方法传入要发送请求的路径及方法和请求头等参数
  2. 判断返回的状态是否成功
  3. 使用promsie的then方法获取返回的response对象
  4. 使用response的text方法或json方法获取数据
  • 注意
    该方法旧版本浏览器不支持