Fetch的使用

本文详细介绍了如何使用原生JS(fetch和XMLHttpRequest)进行API请求,包括GET、POST及文件上传,并提供了fetch的封装方法,简化API调用流程。

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

一.简介:
原生JS(fetch和XMLHttpRequest)请求API的一种方式,可以调用.then的方法,可以看成一个promise函数!
二.具体使用:
1.GET请求

 fetch('http://example.com/movies.json')
	  .then(function(response) {
	    return response.json();
	  })
	  .then(function(myJson) {
	    console.log(myJson);
	  })
	  .catch(function(err) {
	    console.log(err);
	  });

1.POST请求:

  var url = 'https://example.com/profile';
	var data = {username: 'example'};
	
	fetch(url, {
	  method: 'POST', // or 'PUT'
	  body: JSON.stringify(data), // data can be `string` or {object}!
	  headers: new Headers({
	    'Content-Type': 'application/json'
	  })
	}).then(res => res.json())
	.then(response => console.log('Success:', response))
	.catch(error => console.error('Error:', error));

3.上传文件:

var formData = new FormData();
	var fileField = document.querySelector("input[type='file']");
	
	formData.append('username', 'abc123');
	formData.append('avatar', fileField.files[0]);
	
	fetch('https://example.com/profile/avatar', {
	  method: 'PUT',
	  body: formData
	})
	.then(response => response.json())
	.then(response => console.log('Success:', response))
	.catch(error => console.error('Error:', error));

三.封装fetch:

/**
	 * 将对象转成 a=1&b=2的形式
	 * @param obj 对象
	 */
	function obj2String(obj, arr = [], idx = 0) {
	  for (let item in obj) {
	    arr[idx++] = [item, obj[item]]
	  }
	  return new URLSearchParams(arr).toString()
	}
	/**
	 * 真正的请求
	 * @param url 请求地址
	 * @param options 请求参数
	 * @param method 请求方式
	 */
	function commonFetcdh(url, options, method = 'GET') {
	  const searchStr = obj2String(options)
	  let initObj = {}
	  if (method === 'GET') { // 如果是GET请求,拼接url
	    url += '?' + searchStr
	    initObj = {
	      method: method,
	      credentials: 'include'
	    }
	  } else {
	    initObj = {
	      method: method,
	      credentials: 'include',
	      headers: new Headers({
	        'Accept': 'application/json',
	        'Content-Type': 'application/x-www-form-urlencoded'
	      }),
	      body: searchStr
	    }
	  }
	  fetch(url, initObj).then((res) => {
	    return res.json()
	  }).then((res) => {
	    return res
	  })
	}
	
	/**
	 * GET请求
	 * @param url 请求地址
	 * @param options 请求参数
	 */
	function GET(url, options) {
	  return commonFetcdh(url, options, 'GET')
	}
	
	/**
	 * POST请求
	 * @param url 请求地址
	 * @param options 请求参数
	 */
	function POST(url, options) {
	  return commonFetcdh(url, options, 'POST')
	}
	调用实例:
	GET('https://www.baidu.com/search/error.html', {a:1,b:2})
	POST('https://www.baidu.com/search/error.html', {a:1,b:2})

四.参考内容:
俱沫:《fetch,终于认识你》https://segmentfault.com/a/1190000011433064;
mdn:《使用fetch》https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch;

### Fetch API 的基本用法 Fetch API 是一种现代的 JavaScript 接口,用于发起网络请求并与服务器交互。它提供了一个灵活而强大的方式来处理 HTTP 请求和响应。 #### 基本语法 `fetch()` 方法接受两个参数:第一个是资源 URL 或 `Request` 对象;第二个是一个可选的配置对象,允许自定义请求行为[^4]。 以下是使用 Fetch API 发起 GET 请求的一个简单例子: ```javascript fetch('https://api.example.com/data') .then(response => { if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` #### 配置不同的请求方法 除了默认的 GET 请求之外,还可以通过设置 `method` 属性指定其他类型的请求,比如 POST、PUT、DELETE 等。下面展示了如何发送带有 JSON 数据体的 POST 请求: ```javascript const postData = { key: 'value' }; fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postData), }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` 对于更复杂的场景,可以创建一个 `Request` 对象以便更好地管理请求细节。 #### 处理 HTML 页面请求 如果目标是从远程获取整个网页的内容,则需注意调整解析逻辑以适应文本而非 JSON 格式的返回值[^3]: ```javascript fetch('https://example.org/') .then(response => response.text()) // 将 Response 转化成字符串形式 .then(html => document.body.innerHTML += html); // 插入到当前文档结构里显示出来 ``` 另外还有像 HEAD 和 OPTIONS 这样的特殊用途的方法也得到了支持,在某些特定情况下非常有用[^1]。 ### 总结 以上介绍了 Fetch API 如何执行基础以及高级别的 HTTP 操作,并提供了几个实际应用中的代码片段作为示范说明其强大功能所在之处。利用这些技巧可以帮助开发者构建更加健壮的应用程序接口调用流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值