使用JS发起接口请求(Fetch)

GET请求:

const url = 'http://localhost:3000/api/select';

// 创建一个Headers对象来添加自定义header

const headers = new Headers();

headers.append('token', 'xxxxx'); // 替换为实际的header名称和值

// 使用fetch发送GET请求,并带上headers

fetch(url, {

  method: 'GET', // 或者可以省略,因为GET是默认方法

  headers: headers, // 将headers对象作为选项的一部分

  mode: 'cors', // 如果跨域请求,需要设置mode为'cors'

  credentials: 'same-origin' // 根据需要设置,如果需要携带cookie等凭证

})

.then(response => {

  // 检查响应是否成功 (状态码在200-299之间)

  if (!response.ok) {

    throw new Error('Network response was not ok');

  }

  // 解析JSON

  return response.json();

})

.then(data => {

  // 处理响应数据

  console.log(data); // 在控制台打印数据

})

.catch(error => {

  console.error('There has been a problem with your fetch operation:', error);

});

POST请求:

const url = 'http://localhost:3000/api/create';

// 创建一个对象作为请求体

const data = {

  name: 'John Doe',

  email: 'johndoe@example.com',

};

// 使用fetch发送POST请求

fetch(url, {

  method: 'POST', // 指定请求方法为POST

  headers: {

    'Content-Type': 'application/json', // 设置请求头,告诉服务器发送的是JSON数据

  },

  body: JSON.stringify(data) // 将JavaScript对象转换为JSON字符串作为请求体

})

.then(response => {

  // 检查响应是否成功 (状态码在200-299之间)

  if (!response.ok) {

    throw new Error('Network response was not ok');

  }

  // 如果需要,可以返回解析后的JSON数据

  return response.json();

})

.then(data => {

  // 处理响应数据

  console.log(data); // 在控制台打印返回的数据

})

.catch(error => {

  console.error('There has been a problem with your fetch operation:', error);

});

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容