147 How To (Not) Send Http Requests

1、axios

安装

npm install axios

使用

import axios from 'axios';

export default {
  data() {
    return {
      // 数据
    };
  },
  methods: {
    fetchDataFromBackend() {
      axios.get('/api/your-endpoint')
       .then(response => {
          // 处理后端返回的数据
          this.someData = response.data;
        })
       .catch(error => {
          console.error('Error fetching data:', error);
        });
    }
  }
};

2、fetch

在浏览器中,fetch是一种用于发送 HTTP 请求的现代方法。以下是关于浏览器fetch的介绍:

一、基本用法

fetch接收一个 URL 作为参数,并返回一个 Promise 对象,该对象在请求完成后解析为一个 Response 对象。

fetch('https://example.com/api/data')
 .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
 .then(data => {
    // 处理返回的数据
    console.log(data);
  })
 .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

二、参数设置

  1. 请求方法和数据

    fetch可以通过配置对象来指定请求方法(如 GET、POST、PUT、DELETE 等)和请求体数据。
       fetch('https://example.com/api/data', {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json'
         },
         body: JSON.stringify({ key: 'value' })
       })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  2. 自定义请求头

    可以设置自定义的请求头,用于传递特定的信息给服务器。
       fetch('https://example.com/api/data', {
         headers: {
           'Authorization': 'Bearer your-token',
           'Custom-Header': 'custom-value'
         }
       })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值