当使用 JavaScript 请求接口时,可以使用以下方法将一个空值传递给接口:

  1. 对象字面量中的空值:可以将一个空对象 '{}' 作为请求的参数传递给接口。
const data = {};
fetch('/api/endpoint', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
  1. 空字符串:可以将一个空字符串 '' 作为请求的参数传递给接口。
const data = '';
fetch('/api/endpoint', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
  1. null 或 undefined:可以将 null 或 undefined 作为请求的参数传递给接口。
const data = null; // 或 const data = undefined;
fetch('/api/endpoint', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

根据接口的要求,选择适合的方法将空值传递给接口。


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

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