在 Fetch API 的 POST 请求中,可以使用以下方法接收数据:

  1. 使用 json() 方法解析响应数据为 JSON 格式:
fetch(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error(error);
});
  1. 使用 text() 方法解析响应数据为文本格式:
fetch(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.text())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error(error);
});
  1. 使用 formData() 方法解析响应数据为表单格式:
const formData = new FormData();
formData.append('username', 'John');
formData.append('email', 'john@example.com');

fetch(url, {
  method: 'POST',
  body: formData
})
.then(response => response.formData())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error(error);
});
Fetch POST 请求接收数据方法详解

原文地址: https://www.cveoy.top/t/topic/mzGr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录