ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

fetch 基本使用

2022-01-28 02:04:07  阅读:176  来源: 互联网

标签:基本 function console 请求 text 使用 data fetch


@

目录


fetch 概述

Fetch API - Web API 接口参考 | MDN

  • Fetch API是新的ajax解决方案,基于Promise实现, Fetch会返回Promise
  • fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象,可看作 ajax 的升级版,更简单易用强大

基本语法结构

/*
url: 请求地址
options: 配置对象
*/
fetch(url, options) // 返回一个promise对象, 可以使用then拿到请求的结果 
	.then(function(data){
		/*
		text()、json() fetch 内部 API
		*/
		return data.text()
		// return data.json()
	})
	.then(function(ret){
		// fetch响应结果
		console.log(ret)
	})
	...
	.catch(fn)
  • url
    在get、delete 请求中,不仅支持查询字符串,还支持路由参数

    fetch('http://localhost:3000/fetch?id=2')
    // 路由参数
    fetch('http://loclahsot:3000/fetch/2')
    
  • options
    配置对象,用来配置请求,有如下常用配置项

    属性 描述
    method String HTTP请求方法,默认为GET (GET、POST、PUT、DELETE)
    body String HTTP的请求参数
    headers Object HTTP的请求头,默认为{}
  • data.text()、data.json()
    它们属于fetchAPI的一部分,它们返回一个Promise实例对象,用于设置响应数据格式

    方法 描述
    text() 将返回体处理成字符串类型
    json() 返回结果和 JSON.parse(responseText) 一样

fetch API 中的 HTTP 请求 举例

fetch 支持 RESTful API,http协议提供的POST,GET,DELETE,UPDATE,PATCH和PUT都支持

使用fetch 发起 GET 请求

method 默认的是 GET 请求

//GET参数传递-传统URL
 fetch('http://localhost:3000/books?id=123', {
   method: 'get'
 })
   .then(function(data){
     return data.text();
   }).then(function(data){
     console.log(data)
   });

 //GET参数传递-restful形式的URL
 fetch('http://localhost:3000/books/456', {
   method: 'get'
 })
   .then(function(data){
     return data.text();
   }).then(function(data){
     console.log(data)
   });

使用 fetch 发起 DELETE 请求

// DELETE请求方式参数传递
fetch('http://localhost:3000/books/789', {
  // 设置 method
  method: 'delete'
})
  .then(function(data){
    return data.text();
  }).then(function(data){
    console.log(data)
  });

使用 fetch 发起 POST 请求

POST请求传参
fetch('http://localhost:3000/books', {
  // 设置请求配置参数
  method: 'post',
  body: 'uname=lisi&pwd=123',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(function(data){
    return data.text();
  }).then(function(data){
    console.log(data)
  });

POST请求传参
fetch('http://localhost:3000/books', {
  method: 'post',
  body: JSON.stringify({
    uname: '张三',
    pwd: '456'
  }),
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(function(data){
    return data.text();
  }).then(function(data){
    console.log(data)
  });

使用 fetch 发起 PUT 请求

fetch('http://localhost:3000/books/123', {
        method: 'put',
        body: JSON.stringify({
            uname: '张三',
            pwd: '789'
        }),
        headers: {
            'Content-Type': 'application/json'
        }
})
	.then(function(data) {
	    return data.text();
	}).then(function(data) {
	    console.log(data)
	});

fetchAPI 中 响应格式

用fetch来获取数据,如果响应正常返回,我们首先看到的是一个response对象,其中包括返回的一堆原始字节,这些字节需要在收到后,需要我们通过调用方法将其转换为相应格式的数据,比如JSONBLOB或者TEXT等等

    /*
      Fetch响应结果的数据格式
    */
    fetch('http://localhost:3000/json').then(function(data){
      // return data.json(); //  将获取到的数据使用 json 转换对象
      return data.text(); //  将获取到的数据 转换成字符串 
    }).then(function(data){
      // console.log(data.uname)
      // console.log(typeof data)
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })

标签:基本,function,console,请求,text,使用,data,fetch
来源: https://www.cnblogs.com/gh-StudyNotes/p/15851737.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有