fetch基本使用

本文介绍了如何在JavaScript中使用fetch API进行网络请求,并结合async/await语法进行异步操作。通过示例展示了从发送请求到解析JSON数据的完整流程,还提供了一个request.js实用函数,用于封装fetch调用,简化数据获取。最后,演示了如何在实际应用中导入并使用这个request函数来执行POST请求。
摘要由CSDN通过智能技术生成

基本使用

fetch(url,options) // url:请求地址,options:请求参数
  .then(response => response.json()) // 将返回的数据json化
  .then(data => console.log(data)); // 对返回的json对象进行操作

与async ,await结合使用

async function postData(url = '', options= {}) {
  const response = await fetch(url, options)
  return response.json();
}
postData(url, options)
  .then(data => {
    console.log(data);
  });

写一个简单的request.js文件

function parseJSON(response) {
  return response.json();
}
export default async function request(url, options) {
  return (
    fetch(url, options)
      .then(parseJSON)
      .then((data) => {
        return data;
      })
      .catch((err) => ({ err }))
  );
}

使用示例

import request from "@/utils/request";
export async function getData(param) {
  return request(url, {
    method: "POST",
    body: JSON.stringify(param),
  });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值