开发者问题收集

Axios 从数据库删除后出现 404 错误

2020-06-10
893

我正在使用 axios 从我的 React 前端向带有 mongo DB 的 node js express 后端发送删除请求。虽然数据确实从我的数据库中删除了,但我仍然收到错误 404 Not Found。

这是 React 代码

axios
    .delete(`http://localhost:8000/notes/${id}`)
    .then(res => {
      console.log("The response is "+res.data)
    })
    .catch(err => {
      console.log("There was an error "+ JSON.stringify(err.response))
    });

这是 node js express 代码 app.js

app.delete("/notes/:notesId", cors(), function(req, res) {
  const query={_id:req.params.notesId};
  console.log("The notes id is "+ query);  
  Note.findOneAndDelete(query, function(err) {
    if(!err) {
      console.log("The item got successfully deleted");
      res.redirect("/");
    } else {
      console.log(err)
    }
  })
})

请注意,该条目已从我的数据库中删除,但我在浏览器控制台中收到此错误:

xhr.js:178 DELETE http://localhost:8000/ 404 (Not Found)
App.jsx:26 There was an error {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /</pre>\n</body>\n</html>\n","status":404,"statusText":"Not Found","headers":{"content-length":"142","content-type":"text/html; charset=utf-8"},"config":{"url":"http://localhost:8000/notes/5ee130b65dc5f521acf60f38","method":"delete","headers":{"Accept":"application/json, text/plain, */*"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

我试图点击完整的 url 直到 notes id,但它只考虑直到 root

1个回答

尝试修改 res,以便在对象被删除时发送 200 OK 状态。您也可以发送一条消息让前端以这种方式显示

if(!err) {
    res.status(200).json({ message: 'The item got successfully deleted', error: false });
} else {
    res.status(500).json({message : 'Oops and error occurred', error : true});

无论如何,简单的 res.status(200).end(); 也足以满足您的情况。

spaceSentinel
2020-06-10