fetch请求和ajax请求

ajax

1.是XMLHTTPRequest的一个实例

2.只有当状态为200或者304时才会请求成功

3.格式零散,容易出现回调地狱的问题

fetch

1.fetch是基于promise实现的,也可以结合async/await

2.fetch请求默认是不带cookie的,需要设置fetch(URL,{credentials:’include’})。 

Credentials有三种参数:same-origin,include,*

3.服务器返回400 500 状态码时并不会reject,只有网络出错导致请求不能完成时,fetch才会被reject

4.所有版本的 IE 均不支持原生 Fetch

5.fetch是widow的一个方法

 

简单例子:

fetch(url).then(function (response) {
    return response.json()   //执行成功第一步
}).then(function (returnedValue) {
    //执行成功的第二步
}).catch(function (err) {
    //中途的任何地方出错  都会在这里被捕获到
})

注意:
fetch 的第二参数中
1、默认的请求为get请求 可以使用method:post 来进行配置 
2、第一步中的 response有许多方法 json() text() formData()
3、Fetch跨域的时候默认不会带cookie 需要手动的指定 credentials:'include'

使用fetch之后得到的是一个promise对象 在这个promise对象里边再定义执行成功的时候是什么。下面是正确的fetch的使用方法

 var promise=fetch('http://localhost:3000/news', {
        method: 'get'
    }).then(function(response) {
             return  response.json()
    }).catch(function(err) {
        // Error :(
    });
    promise.then(function (data) {
          console.log(data)
    }).catch(function (error) {
        console.log(error)
    })
//练习一, 使用get 和post方式获取数据

//将事件放在组件外部
function getRequest(url) {
    var opts = {
        method:"GET"
    }
    fetch(url,opts)
        .then((response) => {
            return response.text();  //返回一个带有文本的对象
        })
        .then((responseText) => {
            alert(responseText)
        })
        .catch((error) => {
            alert(error)
        })

}
//Post方法, 需要请求体body
/*
* FromData
* 主要用于序列化表单以及创建与表单格式相同的数据
*
* var data = new FormData();
* data.append("name","hello");
* append方法接收两个参数,键和值(key,value),分别表示表单字段的名字 和 字段的值,可添加多个
*
* 在jQuery中,"key1=value1&key2=valu2" 作为参数传入对象框架,会自动分装成FormData形式
* 在Fetch 中,进行post进行post请求,需要自动创建FormData对象传给body
*
* */
function postRequest(url) {
    //将"key1=value1&key2=valu2" 形式封装整FromData形式
    let formData = new FormData();
    formData.append("username","hello");
    formData.append("password","1111aaaa");

    var opts = {
        method:"POST",   //请求方法
        body:formData,   //请求体
     headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },

    }

    fetch(url,opts)
        .then((response) => {
//你可以在这个时候将Promise对象转换成json对象:response.json()
    //转换成json对象后return,给下一步的.then处理
            return response.text
        })
        .then((responseText) => {
            alert(responseText)
        })
        .catch((error) => {
            alert(error)
        })
}

fetch和ajax 的主要区别

1、fetch()返回的promise将不会拒绝http的错误状态,即使响应是一个HTTP 404或者500 
2、在默认情况下 fetch不会接受或者发送cookies

使用fetch开发项目的时候的问题

1、所有的IE浏览器都不会支持 fetch()方法
2、服务器端返回 状态码 400 500的时候 不会reject

 

猜你喜欢

转载自www.cnblogs.com/baixiaoxiao/p/11302814.html