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 0000000000000000000000000000000000000000..f5a49d4ac124a1b774564f1345ab185570e7c32f --- /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); // 处理错误 + }); +``` +