📜  如何发送 post 请求 js fetch - Javascript (1)

📅  最后修改于: 2023-12-03 14:52:11.190000             🧑  作者: Mango

如何发送 post 请求 js fetch - Javascript

在前端开发中,与后端进行数据交互是非常常见的需求,而发送 post 请求是其中一种常见的请求方式。本文将介绍如何在 Javascript 中使用 fetch API 发送 post 请求。

fetch API

fetch 是一种基于 promise 的 HTTP 请求 API,可以在浏览器中发送 HTTP 请求。fetch API 的用法相对简单,一个简单的 GET 请求代码如下:

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

其中,.then(response => response.json()) 是将服务器的响应转化为 JSON 格式。fetch API 其他用法可参考官方文档

发送 POST 请求使用示例

下面是一个使用 fetch API 发送 POST 请求的示例代码:

const url = 'http://example.com/post-data';
const data = { name: 'Lucy', age: 23 };

fetch(url, {
  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));

其中,url 是请求地址,data 是要发送的数据。在发送 POST 请求时,需要在 fetch 的第二个参数中传入一些选项:

  • method: 请求的方法,这里要设置为 POST。
  • headers: 表示消息头,这里设置 Content-Type 为 application/json,表示发送的数据格式为 JSON。
  • body: 表示请求的数据,需要将 JSON 对象转化为字符串。

在 fetch API 中,通过 .then(response => response.json()) 将服务器返回的响应转为 JSON 格式。使用 .catch() 来处理请求出错的情况。

总结

发送 POST 请求可以通过 fetch API 轻松实现,只需要在 fetch 的第二个参数中传入相应的选项即可。以 JSON 数据格式为例,需要在 headers 中设置 Content-Type: application/json,同时需要将 JSON 对象转化为字符串存放在 body 中。

以上就是如何使用 Javascript fetch API 发送 POST 请求的介绍。