fetch api

Making fetch requestsEDIT

A basic fetch request is really simple to set up. Have a look at the following code:

var myImage = document.querySelector('img');

fetch('flowers.jpg')
.then(function(response) {
  return response.blob();
})
.then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Here we are fetching an image across the network and inserting it into an <img> element. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).

This is just an HTTP response of course, not the actual image. To extract the image body content from the response, we use the blob() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)


其他例子 :

fetch('https://cnodejs.org/api/v1/topics', {
            method: 'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: `accesstoken=${user.token}&tab=${tab.value}&title=${title.value}&content=${content.value}`
        }).then(res => res.json()).then(json => {
            if(json.success) {
                this.setState({
                    show: true,
                    msg: '发表成功',
                });
                fetchTopicContent(json.topic_id);
                setTimeout(() => {this.context.router.push(`/topic/${json.topic_id}`)}, 1000);
            } else {
                this.setState({
                    show: true,
                    msg: json.error_msg,
                });
            }
        })
    }


摘自  http://cn.redux.js.org/docs/advanced/AsyncActions.html

fetch 使用须知

本示例使用了 fetch API。它是替代 XMLHttpRequest 用来发送网络请求的非常新的 API。由于目前大多数浏览器原生还不支持它,建议你使用 isomorphic-fetch 库:

// 每次使用 `fetch` 前都这样调用一下
import fetch from 'isomorphic-fetch'

在底层,它在浏览器端使用 whatwg-fetch polyfill,在服务器端使用 node-fetch,所以如果当你把应用改成同构时,并不需要改变 API 请求。

注意,fetch polyfill 假设你已经使用了 Promise 的 polyfill。确保你使用 Promise polyfill 的一个最简单的办法是在所有应用代码前启用 Babel 的 ES6 polyfill:

// 在应用中其它任何代码执行前调用一次
import 'babel-polyfill'


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值