Fetch发送请求

66 阅读1分钟

Fetch

Fetch 是一种用于发送网络请求的 API,可以用于获取资源、上传文件、向服务器发送命令等。取代了传统的 XMLHttpRequest。

发送 GET 请求

fetch('https://api.example.com/data')

  .then(response => response.json())
  
  .then(data => {
  
    // 处理返回的数据
    
    console.log(data);
    
  })
  .catch(error => {
  
    // 处理请求错误
    
    console.error(error);
    
  });
  

发送 POST 请求并添加请求头

fetch('https://api.example.com/data', {

  method: 'POST',
  
  headers: {
  
    'Content-Type': 'application/json',
    
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    
  },
  
  body: JSON.stringify({ key: 'value' })
  
})

  .then(response => response.json())
  
  .then(data => {
  
    // 处理返回的数据
    
    console.log(data);
    
  })
  
  .catch(error => {
  
    // 处理请求错误
    
    console.error(error);
    
  });
以上示例代码演示了 Fetch 发送请求的基本概念