fetch简介和axios介绍(引用链接、get和post请求方式、自定义请求、请求拦截、官网)

本文详细介绍了fetch和axios这两种流行的前端HTTP客户端库的使用方法。包括GET和POST请求的不同实现方式,自定义请求创建及拦截器的使用等。适用于希望深入理解这两种工具的前端开发者。

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

目录

fetch

fetch的get请求方式

fetch的post请求方式

axios

引用链接

axios的get请求方式

axios的post请求方式

axios({}).then(res=>{console.log(res)});

例子

自定义请求const ax=axios.create({})

自定义请求拦截

ax.interceptors.request.use(funtion(config){return config},function(error){return Promise.reject(error)})

ax.interceptors.response.use(function(response){return response},function(error){return Promise.reject(error)})

axios官网


fetch

XMLHttpRequest是一个设计粗糙的API,配置和调用方式非常混乱,而且基于事件的异步模型写起来不友好。fetch即用于解决这些问题,然后fetch是基于promise设计的顾搭配下面方式使用,promise不懂得可以看这个链接https://blog.youkuaiyun.com/AIWWY/article/details/115766690

fetch的get请求方式

fetch('./json/test.json?name=pyf&age=18').then(res=>res.json()).then(res=>{console.log(res)})

此时打印出来的是json对象。将res.json()改为res.text()打印的是对象的字符串形式。参数为请求的路径地址,可以携带发送数据。

fetch的post请求方式

有2种请求方式(jQuery默认是第一种)

  1. fetch('',{method:'post', headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'name=pyf&age=100'}).then(res=>res.json()).then(res=>{console.log(res)});
  2. fetch('',{method:'post', headers:{'Content-Type':'application/json'},body:JSON.stringify({name='pyf',age=100})}).then(res=>res.json()).then(res=>{console.log(res)});

同上,第一个参数为请求路径,第二参数为对象,其中设置不同的post方式和传递的数据,注意post请求json数据会报405错误,只能用get请求(使用post请求并且发送的URL是一个具体的资源的时候例如JSON文件,网站解析的时候会把整个URL当作域名解析,也就是说我并没有传参数给服务端,而是直接访问服务端的具体资源,所以要用get请求)。

注意fetch默认不带cookie数据(jQuery和原生AJAX都是默认会带的),要想添加的话,在第二个参数的对象中添加属性credentials,其取值有3种:

  1. 'omit':为默认的,表示不带cookie数据。
  2. 'same-origin':表示cookie只能同域发送不能跨域发送。
  3. 'include':表示既可以同域发送也可以跨域发送。

 

axios

引用链接

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

axios的get请求方式

 axios.get('json/test.json?name=pyf&age=18').then(res=>{console.log(res.data)})

此时打印出来的是json对象。参数为请求的路径地址,可以携带发送数据。

 

axios的post请求方式

2种请求方式:

  1. axios.post('',"name=pyf&age=18").then(res=>{console.log(res)});
  2.  axios.post('',{name:'pyf',age:18}).then(res=>{console.log(res)});

同上,第一个参数为请求路径,第二参数为字符串或对象携带请求数据。

 

axios({}).then(res=>{console.log(res)});

通过直接在对象中设置请求内容,例如{url:'',headers:{'':''},method:'get',data:{}},headers表示请求头,里面的属性要为字符串格式。

例子

当我们请求卖座电影的url链接时(该地址在Headers中的Response Headers中的Access-Control-Allow-Oringin:*代表允许跨域请求,所以可以直接请求),但它需要验证信息,例如下图的X-Clinet-Info和X-Host,此时我们可以通过上面的方法请求数据,代码如下:

 axios({
      url: 'https://m.maizuo.com/gateway?cityId=440300&pageNum=1&pageSize=10&type=1&k=5823016',
      headers: {
        'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"16225381261882046079172609"}',
        'X-Host': 'mall.film-ticket.film.list'
      }
    }).then(res => { console.log(res.data) })

自定义请求const ax=axios.create({})

设置axios中的基础配置传给分装的函数,例如const ax=axios.create({baseURL:'https://m.maizuo.com/',timeout:10000,headers:{ 'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"16225381261882046079172609"}','X-Host': 'mall.film-ticket.film.list'}}),其中timeout表示请求最长时间(单位毫秒),上图中的请求便可以写成ax({url:gateway?cityId=440300&pageNum=1&pageSize=10&type=1&k=5823016'})。

自定义请求拦截

ax.interceptors.request.use(funtion(config){return config},function(error){return Promise.reject(error)})

请求拦截,请求前调用第一个函数,config是一个对象,可以通过config.headers配置请求头的信息。第二个函数是请求失败执行的函数。

ax.interceptors.response.use(function(response){return response},function(error){return Promise.reject(error)})

响应拦截,当服务端成功响应时执行第一个函数,response服务器端返回的具体数据信息,与业务 axios 接收的数据一致,失败时执行第二个函数。

axios官网

http://www.axios-js.com/zh-cn/docs/

 

### 封装 AxiosPOST GET 请求 为了更好地理解如何使用 TypeScript 来封装 Axios 进行 HTTP 请求,下面提供了一个详细的指南以及最佳实践。 #### 安装依赖项 首先,在项目中安装 `axios` 及其类型定义文件: ```bash npm install axios @types/axios --save-dev ``` 这一步骤确保了可以在 TypeScript 中获得完整的类型支持[^2]。 #### 创建 API 实例服务层 创建一个新的服务类来处理所有的网络请求。这种方法有助于保持代码整洁并易于维护。 ```typescript // src/services/apiService.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; class ApiService { private instance: AxiosInstance; constructor(baseURL?: string) { this.instance = axios.create({ baseURL, timeout: 10000, headers: { 'Content-Type': 'application/json', }, }); // 添加请求拦截器 this.instance.interceptors.request.use( (config: AxiosRequestConfig): AxiosRequestConfig => { // 在发送请求之前做些什么 console.log('Sending Request:', config.url); return config; }, (error) => Promise.reject(error), ); // 添加响应拦截器 this.instance.interceptors.response.use( (response: AxiosResponse<any>): any => response.data, (error) => Promise.reject(error), ); } public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> { return this.instance.get(url, config).then((res) => res as unknown as T); } public post<T>( url: string, data?: object | null, config?: AxiosRequestConfig ): Promise<T> { return this.instance.post(url, data || {}, config).then( (res) => res as unknown as T, ); } } export default new ApiService(); ``` 上述代码展示了如何通过自定义配置初始化 Axios设置通用的请求响应拦截器。这里还实现了两个泛型方法——`get` `post`,它们可以接受 URL 参数其他可选参数,并返回指定类型的承诺对象[^1]。 #### 使用封装的服务发起请求 现在可以通过导入这个服务模块并在应用程序中的任何地方调用来简化对远程资源的操作。 ```typescript // Example usage within a component or another service file. import apiService from './services/apiService'; async function fetchData() { try { const result = await apiService.get<{ message: string }>('/api/data'); console.log(result.message); // Handle success case here... } catch (err) { console.error(err); // Handle error case here... } } ``` 此示例说明了如何利用前面定义好的 `ApiService` 类来进行数据获取操作。注意这里的 `<{ message: string }>` 是用于指明预期接收的数据结构的一部分,从而增强了编译期间的安全性开发体验[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值