天天看点

es6的fetch函数

GET请求写法

<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>fetch的GET请求</title>
</head>
<body>
	<script>
	var url = '/getMessage' + '?type=1&id=1'
        fetch(url,{
            method: 'GET'       // 默认为GET
        }).then(function(response) {
            // response.json()是一个promise对象,请求成功后里面执行了resolve()因此数据传到下一个then
            return response.json()
        }).then(function(data) {
            console.log(data)
        }).catch(function(e) {
            console.log('Oops, error')
        })
	</script>
</body>
</html>
           

POST请求写法

<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>fetch的POST请求</title>
</head>
<body>
	<script>
	// 写法一
	var data = new FormData()
        data.append('type','1')
        data.append('id','1')
	var url = '/getMessage'
        fetch(url,{
            method: 'POST',
            body: data
        }).then(function(response) {
            // response.json()是一个promise对象,请求成功后里面执行了resolve()因此数据传到下一个then
            return response.json()
        }).then(function(data) {
            console.log(data)
        }).catch(function(e) {
            console.log('error')
        })

        // 写法二(浏览器可能不支持import语法,需要用babel转)
        import qs from 'qs'
	var url = '/getMessage'
        fetch(url,{
            method: 'POST',
            body: qs.stringify({
		        type: 1,
		        id: 1
		  })
        }).then(function(response) {
            // response.json()是一个promise对象,请求成功后里面执行了resolve()因此数据传到下一个then
            return response.json()
        }).then(function(data) {
            console.log(data)
        }).catch(function(e) {
            console.log('error')
        })
	</script>
</body>
</html>
           

fetch的参数:

第一个是url即请求的处理路径; 

第二个是初始化信息,包括以下几种:

(1)method:请求方法,常用的有get和post;

(2)headers:请求头信息,最常用的就是表单格式的数据:"Content-type":"application/x-www-form-urlencoded";

(3)mode:控制是否允许跨域。same-origin(同源请求)、no-cors(默认)和cors(允许跨域请求);

(4)cache:关于缓存的一些设置;

(5)body:要发送到后台的参数,可以为ArrayBuffer,String,FormData等类型;

es6的fetch函数

继续阅读