以下是使用fetch发起post请求的JavaScript代码示例:

const url = 'https://example.com/api';
const data = {
  name: 'John Smith',
  email: 'john@example.com'
};

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));

在上面的示例中,我们首先定义了要请求的URL和要发送的数据。然后,我们使用fetch函数发起一个POST请求。在fetch函数中,我们指定了请求的方法为POST,并且将数据作为JSON字符串发送。此外,我们还为请求添加了一个“Content-Type”标头,以确保服务器知道我们发送的是JSON数据。

一旦请求成功,我们将收到一个响应对象。我们可以通过调用response.json()方法来将响应体解析为JSON格式的数据。最后,我们将响应数据打印到控制台中。如果请求失败,则会在控制台中打印错误信息。

javascript中用fetch发起post请求的代码

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

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