I'm learning the The University of Helsinki's Fullstack lesson , I can POST, and GET, but why I can't DELETE.
I used VS Code REST Client, this is REST Client code, I use it to test, POST and GET works good
POST http://localhost:3002/api/persons
Content-Type: application/json
{
"name": "re",
"number": "001"
}
###
DELETE http://localhost:3002/api/person/600974589e4e3b4a1562fd75
###
GET http://localhost:3002/api/person/600974589e4e3b4a1562fd75
This is my javascript code
index.js
app.post('/api/person', (req, res) => {
const body = req.body
if((!body.number) || (!body.name)){
return res.status(400).json({
error: 'Number or name is not exist!'
})
}
const newperson = new Phonebook({
name: body.name,
number: body.number,
date: new Date(),
})
newperson.save().then(savePerson => {
res.json(savePerson)
})
})
app.get('/api/person/:id', (req, res, next) => {
Phonebook.findById(req.params.id).then(person => {
if(person){
res.json(person)
}
else{
res.status(404).end()
}
})
.catch(error => next(error))
})
app.delete('api/person/:id', (request, response, next) => {
Phonebook.findByIdAndRemove(request.params.id)
.then(result => {
response.status(204).end()
})
.catch(error => next(error))
})
DELETE error
HTTP/1.1 404 Not Found
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 27
ETag: W/"1b-MMxRBlHxrLoIiEJggegnVLYwVTY"
Date: Sat, 23 Jan 2021 05:52:21 GMT
Connection: close
{
"error": "unkown endpoint"
}
I try to find the MongoDB Atlas log, but can't find it.
use this middleware in app.js at first file before call route
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
next();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.