Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

javascript - I cam use POST and GET, but why I can't use DELETE in MongoDB Atlas

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...