fetch方法

在《深入浅出React和Redux》一书中,介绍react与服务器端交互时,用了fetch方法:https://github.com/github/fetch。该网址上有各种使用例子。

安装:、

npm install whatwg-fetch --save

webpack上使用时:

entry: ['whatwg-fetch', ...]

For Babel and ES2015+:

import 'whatwg-fetch'

fetch方法现代浏览器或多或少原生支持,但是旧版不支持,所以需要下载promise fillpoly:https://github.com/taylorhakes/promise-polyfill。

npm install promise-polyfill --save-exact
1 import Promise from 'promise-polyfill'; 
2 
3 // To add to window
4 if (!window.Promise) {
5   window.Promise = Promise;
6 }

基本使用方法如上。

不过看github上所说,也只支持到IE8+,足够了。

 1 fetch('https://mywebsite.com/endpoint/',
 2  {
 3   method: 'POST', 
 4   headers: { 'Accept': 'application/json',
 5         'Content-Type': 'application/json', }, 
 6   body: JSON.stringify({
 7         firstParam: 'yourValue',
 8         secondParam: 'yourOtherValue', }) 
 9     })
10 
11 .then(function(res){
12   console.log(res)
13 })

只写一个url参数的话,就相当于一般的get方法。

 
原文地址:https://www.cnblogs.com/alan2kat/p/7522746.html