es6的fetch函数

本文介绍了ES6中fetch函数的使用,包括GET和POST请求的写法,以及fetch参数的详细说明,如method、headers、mode和body等,特别强调了如何进行跨域请求和设置请求头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GET请求写法

<!DOCTYPE html>
<html lang="en">
<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 lang="en">
<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等类型;
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值