[英]in JS, how to delete ALL items in a JSON file?
Im running a json server locally (npx json-server extras/db.json) (localhost 3000) and the db.json file is shown at the end of this request.我在本地运行 json 服务器(npx json-server extras/db.json)(localhost 3000),db.json 文件显示在此请求的末尾。 I am able to delete a specific item by id as shown immediately below.
我可以按 id 删除特定项目,如下所示。
How do I delete ALL items?如何删除所有项目?
(I tried url "http://localhost:3000/expenses" (which displays all items in browser) but get error "DELETE http://localhost:3000/expenses 404 (Not Found)" and it does not delete.) (我尝试了 url "http://localhost:3000/expenses" (在浏览器中显示所有项目)但得到错误 "DELETE http://localhost:3000/expenses 404 (Not Found)" 并且它没有删除。)
I can delete a specific item using:我可以使用以下方法删除特定项目:
export async function deleteExp(id) {
const settings = {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
}
try {
const url = `http://localhost:3000/expenses/${id}`
const response = await fetch(url, settings)
const data = await response.json()
return data
} catch (e) {
console.log('Error', e)
return e
}
}
JSON file (db.json) JSON 文件 (db.json)
{
"expenses": [
{
"id": 22,
"name": "car payment",
"amount": 300
},
{
"id": 23,
"name": "student loan",
"amount": 400
},
{
"id": 24,
"name": "credit card",
"amount": 800
}
]
}
You can delete all items, by looping over the array of expenses
;您可以通过遍历
expenses
数组来删除所有项目; and each loop call the function deleteExp(id)
with the id of expense
:并且每个循环调用 function
deleteExp(id)
与expense
id :
const expenses = {
expenses: [
{
id: 22,
name: "car payment",
amount: 300,
},
{
id: 23,
name: "student loan",
amount: 400,
},
{
id: 24,
name: "credit card",
amount: 800,
},
],
};
for (const expense of expenses) {
await deleteExp(expense.id);
}
BUT Note this is not an efficient way of doing delete all items, To do so you need to make a route /expenses
with delete
method in backend , so there do your process of deleting items!但是请注意,这不是删除所有项目的有效方法,为此,您需要在后端使用
delete
方法创建路线/expenses
,因此您可以执行删除项目的过程!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.