fetch post 类型 传递 json 格式数据
在使用 Fetch API 进行 POST 请求时,可以通过设置请求的 headers 来指定请求的 Content-Type 为 application/json,然后将数据转换为 JSON 格式的字符串,作为请求的 body 传递。具体示例代码如下:
const data = {
name: 'John',
age: 30,
email: 'john@example.com'
};
fetch('https://example.com/api/users', {
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));
在上面的示例代码中,我们首先定义了一个包含 name、age 和 email 属性的对象 data,然后在 Fetch API 的 POST 请求中,通过设置 headers 的 Content-Type 为 application/json,将 data 对象转换为 JSON 格式的字符串,并将其作为请求的 body 参数传递。最后,我们使用 Promise 对象的 then 方法来处理响应结果,并使用 console.log 来输出响应数据。如果请求出现错误,我们使用 catch 方法来捕获错误并输出错误信息。
原文地址: https://www.cveoy.top/t/topic/b5WU 著作权归作者所有。请勿转载和采集!