这是使用 JS 中的 fetch 发送请求的完整指南

2025-06-11

这是使用 JS 中的 fetch 发送请求的完整指南

嗨,我是Aya Bouchiha,在这个美好的日子里,我将讨论使用 fetch 在 javascript 中发送请求。

什么是 GET 请求

GET:是用于从指定服务器获取或检索数据或信息的请求。

使用 then 和 catch 进行编码

const getTodo = (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    fetch(url)
        .then((response) => response.json())
        .then((todo) => console.log(todo))
        .catch((e) => console.log('something went wrong ;(', e));
};
getTodo(1);
Enter fullscreen mode Exit fullscreen mode

使用 async 和 await 的代码

方法 1

const getTodo = async (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    try {
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
getTodo(1);
Enter fullscreen mode Exit fullscreen mode

方法 2

const getTodo = async (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    try {
        const data = await (await fetch(url)).json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
getTodo(1);
Enter fullscreen mode Exit fullscreen mode

什么是 POST 请求

POST:是用于向特定服务器发送信息或数据的请求。

使用 then 和 catch 进行 POST 请求

const postTodo = (todo) => {
  fetch('https://jsonplaceholder.typicode.com/posts',{
    method:'POST',
    body:JSON.stringify(todo),
    headers:{
      'header-name':'header-value'
    }
  }).then(response => response.json())
    .then(data => console.log(data) /* {id:101} */)
    .catch(e => console.log('something went wrong :(', e))
}
const data = {
  title: 'buy food',
  body: "buy healthy food",
  userId: 8,
};
postTodo(data);
Enter fullscreen mode Exit fullscreen mode

使用 async 和 await 进行 POST 请求

const postTodo = async (todo) => {
  try {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts',{
    method:'POST',
    headers:{
      'header-name': 'header-value'
    },
    body:JSON.stringify(todo)
  })
  const data = await response.json();
  console.log(data); // {id:101}
  }catch(e){
    console.log('something went wrong :(', e)
  }
}
const data = {
  title: 'buy food',
  body: "buy healthy food",
  userId: 8,
};
postTodo(data);
Enter fullscreen mode Exit fullscreen mode

什么是 PUT 请求

PUT:是用于在特定服务器中创建或更新资源的请求。

使用 then & catch 发送 PUT 请求

const putTodo = (todo) => {
    const method = 'PUT';
    const headers = {
        'Content-type': 'application/json; charset=UTF-8',
        'header-name': 'header-value',
    };
    fetch('https://jsonplaceholder.typicode.com/posts/1', {
        method,
        headers,
        body: JSON.stringify(todo),
    })
        .then((response) => response.json())
        .then((data) => console.log(data))
        .catch((e) => console.log('something went wrong :(', e));
};
const data = {
    id: 1,
    title: 'this is a title',
    body: 'body!',
    userId: 13,
};
putTodo(data);
Enter fullscreen mode Exit fullscreen mode

安慰:

{id: 1, title: "this is a title", body: "body!", userId: 13}
Enter fullscreen mode Exit fullscreen mode

使用 async & await 发送 PUT 请求

const putTodo = async (todo) => {
    const method = 'PUT';
    const headers = {
        'Content-type': 'application/json; charset=UTF-8',
        'header-name': 'header-value',
    };
    try {
        const response = await fetch(
            'https://jsonplaceholder.typicode.com/posts/1',
            { method, headers, body: JSON.stringify(todo) },
        );
        const data = await response.json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
const data = {
    id: 1,
    title: 'this is a title',
    body: 'body!',
    userId: 13,
};
putTodo(data);
Enter fullscreen mode Exit fullscreen mode

安慰:

{id: 1, title: "this is a title", body: "body!", userId: 13}
Enter fullscreen mode Exit fullscreen mode

什么是 DELETE 请求

DELETE:是用于删除服务器中的特定资源的请求。

使用 then & catch 发送 DELETE 请求

const id = 5;
const deleteTodo = (todoId) => {
  const url = `https://jsonplaceholder.typicode.com/posts/${todoId}`;
  const method  = 'DELETE'
  fetch(url,{method})
  .then(response => console.log(response.status)/*200*/)
  .catch(e=> console.log('something went wrong',e))
};
deleteTodo(id);
Enter fullscreen mode Exit fullscreen mode

使用异步和等待发送 DELETE 请求

const id = 5;
const deleteTodo = async (todoId) => {
  const url = `https://jsonplaceholder.typicode.com/posts/${todoId}`;
  const method  = 'DELETE';
  try {
    const response = fetch(url, {method});
    console.log((await response).status)// 200
  }catch(e){
    console.log('something went wrong', e);
  }
} 
deleteTodo(id);
Enter fullscreen mode Exit fullscreen mode

祝你有美好的一天!

链接链接 https://dev.to/ayabouchiha/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js-53ae
PREV
让我们阅读 – 精炼 Ruby 编程 – 第 1 章 – 充分利用核心类
NEXT
AWS 完善架构框架 | AWS 白皮书摘要 框架的五大支柱 通用设计原则 (1) 卓越运营 (2) 安全性 (3) 可靠性 (4) 性能效率 (5) 成本优化 (6) 可持续性