fetch 在node中使用

2018-07-20  本文已影响0人  天涯笑笑生

一、前言

二、使用

为了使更多浏览器支持需要下载isomorphic-fetch,而fetch 使用的是promise 所以还需要es6-promise来支持更多的浏览器

npm install --save isomorphic-fetch es6-promise
require('es6-promise').polyfill();
require('isomorphic-fetch');

 fetch('/conf', { // URL如不写http等,则会使用host自动补全
            method: 'POST',
            body:JSON.stringify({user:this.state.user, password:this.state.password}),
            headers: new Headers({
                'Content-Type': 'application/json', //发送类型
                'Accept': 'application/json' // 通过头指定,获取的数据类型是JSON
            })
        })
            .then((res)=>{
                return res.json() // 返回一个Promise,可以解析成JSON
            })
            .then((res)=>{
                console.log(res) // 获取JSON数据
            })

参考

fetch,终于认识你
阮一峰的promise

React 推荐的三个AJAX库

上一篇 下一篇

猜你喜欢

热点阅读