From 4f1d8f37093877a5b0fabc130a32c6701dfacdc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E7=8E=89=E6=9D=AD?= <2150097635@example.com> Date: Sun, 19 May 2024 21:08:20 +0800 Subject: [PATCH] , --- .../20240514.API\344\270\216REST.md" | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 "\351\273\204\347\216\211\346\235\255/20240514.API\344\270\216REST.md" diff --git "a/\351\273\204\347\216\211\346\235\255/20240514.API\344\270\216REST.md" "b/\351\273\204\347\216\211\346\235\255/20240514.API\344\270\216REST.md" new file mode 100644 index 0000000..f5a49d4 --- /dev/null +++ "b/\351\273\204\347\216\211\346\235\255/20240514.API\344\270\216REST.md" @@ -0,0 +1,61 @@ +使用Fetch API可以方便地进行RESTful API的调用。 +```javascript +// 发起GET请求获取所有项 +fetch('http://your-api-url/items') + .then(response => response.json()) + .then(data => { + console.log(data); // 处理返回的数据 + }) + .catch(error => { + console.error('Error:', error); // 处理错误 + }); + +// 发起POST请求创建新项 +const newItem = { name: 'New Item' }; +fetch('http://your-api-url/items', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(newItem) +}) + .then(response => response.json()) + .then(data => { + console.log(data); // 处理返回的数据 + }) + .catch(error => { + console.error('Error:', error); // 处理错误 + }); + +// 发起PUT请求更新特定项 +const itemId = 1; +const updatedItem = { name: 'Updated Item' }; +fetch(`http://your-api-url/items/${itemId}`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(updatedItem) +}) + .then(response => response.json()) + .then(data => { + console.log(data); // 处理返回的数据 + }) + .catch(error => { + console.error('Error:', error); // 处理错误 + }); + +// 发起DELETE请求删除特定项 +const itemId = 1; +fetch(`http://your-api-url/items/${itemId}`, { + method: 'DELETE' +}) + .then(response => response.json()) + .then(data => { + console.log(data); // 处理返回的数据 + }) + .catch(error => { + console.error('Error:', error); // 处理错误 + }); +``` + -- Gitee