美文网首页前端
Fetch 优雅的http请求

Fetch 优雅的http请求

作者: 雨中漫步的北极熊 | 来源:发表于2016-10-13 16:13 被阅读1779次

JavaScript 通过XMLHttpRequest(XHR)来执行异步请求。它在设计上不符合职责分离原则,将输入、输出和用事件来跟踪的状态混杂在一个对象里。

这与最近JavaScript流行的Promise以及基于生成器的异步编程模型,匹配不够协调。

新的 Fetch API打算修正上面提到的那些缺陷。它引入一个实用的函数fetch()用来简洁捕捉从网络上检索一个资源的意图。

它尝试优化:

             支持异步编程

             离线性能更佳

             兼容主流浏览器,IE6, IE7, IE8…..

             简单,可靠,好用

推荐做法

安装


$ npm install fetch-polyfill2 --save

$ npm install bluebird -- save

$ npm install json3 -- save

使用


constloginurl="http://192.168.1.50:8080/user/login";

fetch(loginurl, {

method:'POST',

headers: {

'Accept':'application/json',

'Content-Type':'application/json'

},

body:{

"phone":this.state.phone,

"password":this.state.password

}

}).then(function(response){

returnresponse.json()

}).then(function(json){

console.log('parsed json', json)

}).catch(function(ex){

console.log('parsing failed', ex)

})

localStorage 指导


此处推荐使用store.js操作localStorage,理由如下:

可靠,支持各大主流浏览器

支持json格式存储

简单,好用

安装

下载目标文件,链接


// 载入文件

init()

functioninit(){

//判断浏览器支持情况

if(!store.enabled) {

alert('Local storage is not supported by your browser. Please disable "Private Mode", or upgrade to a modern browser.')

return

}

varuser = store.get('user')

// ... and so on ...

}

使用API

// Store 'marcus' at 'username'

store.set('username','marcus')

// Get 'username'

store.get('username')

// Remove 'username'

store.remove('username')

// Clear all keys

store.clear()

// Store an object literal - store.js uses JSON.stringify under the hood

store.set('user', { name:'marcus', likes:'javascript'})

// Get the stored object - store.js uses JSON.parse under the hood

varuser = store.get('user')

alert(user.name +' likes '+ user.likes)

// Get all stored values

store.getAll().user.name =='marcus'

// Loop over all stored values

store.forEach(function(key, val){

console.log(key,'==', val)

})

相关文章

  • Fetch 优雅的http请求

    JavaScript 通过XMLHttpRequest(XHR)来执行异步请求。它在设计上不符合职责分离原则,将输...

  • fetch记录一下子

    1.原生http请求 2.fetch请求 3.上面是封装多得fetch,直接使用的fetch fetch请求对某些...

  • JS异步处理系列二 XHR Fetch

    参考AJAX 之 XHR, jQuery, Fetch 的对比使用更优雅的异步请求API——fetch 一、原生 ...

  • Fetch请求与数据Mock

    Fetch安装 书籍:入门: 图解http精通: 图解http权威指南 get请求示例: fetch是引用了插件之...

  • Fetch数据请求

    fetch:是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch:不是ajax的...

  • ajax、axios、fetch

    fetch: 是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的...

  • Fetch

    fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一...

  • 使用 Fetch进行http请求

    fetch()是 XMLHttpRequest 的升级版,用于在 JavaScript 脚本里面发出 HTTP 请求

  • React Naitve 网络请求

    React Native 网络 [React-Native Fetch方法发送网络请求](http://www.q...

  • 前端进阶(2)使用fetch/axios时, 如何取消http请

    前端进阶(2)使用fetch/axios时, 如何取消http请求[https://jackniu81.githu...

网友评论

本文标题:Fetch 优雅的http请求

本文链接:https://www.haomeiwen.com/subject/ruwwyttx.html