首页 > 解决方案 > 如何使用 JS Fatch Api 发布 JSON 有效负载(名称、电子邮件)

问题描述

如何使用 JS Fatch api 函数发布 JSON 有效负载,此外,请求必须包含不记名(令牌)授权标头

标签: javascriptjson

解决方案


你好,尝试使用这个例子,它会有所帮助

   async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

因此,此代码将帮助您传递数据和所需的标头或参考https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


推荐阅读