Making fetch requests
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'