我正在尝试根据针对MERN堆栈的教程来创建PUT路由。
型号:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const toDoSchema = new Schema({
//taskNum: {type: Number, required: true},
task: {type: String, required: true},
//progress: {type: String, required: true},
//difficulty: {type: Number, required: true}
});
const toDo = mongoose.model("toDo", toDoSchema);
module.exports = toDo
API:
const express = require('express');
const router = express.Router();
//ToDo Model
const ToDo= require('../../models/toDo');
// @route GET api/toDo
// @desc GET all to dos
// @access Public
router.get('/', (req, res) => {
ToDo.find()
.sort({ taskNum: -1 })
.then(toDo => res.json(toDo))
});
// @route POST api/toDo
// @desc create a new to dos
// @access Public
router.post('/', (req, res) => {
const newToDo = new ToDo({
//taskNum: req.body.taskNum,
task: req.body.task,
//progress: req.body.progress,
//difficulty: req.body.difficulty
})
newToDo.save().then(toDo => res.json(toDo));
});
// @route DELETE api/toDo/:id
// @desc Delete a to do
// @access Public
router.delete('/:id', (req, res) => {
ToDo.findById(req.params.id)
.then(toDo => toDo.remove().then(() => res.json( {success: true } )))
.catch(err => res.status(404).json( {success: false } ));
});
// @route UPDATE api/toDo/:id
// @desc Update a to do
// @access Public
router.put('/:id', (req, res) => {
ToDo.findById(req.params.id)
.then(toDo => toDo.set({ task: req.body.task }).then(() => res.json( {success: true } )))
.catch(err => res.status(404).json( {success: false} ));
});
module.exports = router;
我正在测试Postman中的代码,并不断收到Cannot PUT错误消息。
所有其他路线都工作得很好,我只是停留在这个终点。关于我应该改变什么的任何想法?
答案 0 :(得分:0)
确保您正在通过 body 发送数据。尝试记录 req.params.id 和 req.body.task 的值>尝试这样的事情。使用findOneAndUpdate
// @route UPDATE api/toDo/:id
// @desc Update a to do
// @access Public
router.put('/:id', (req, res) => {
ToDo.findOneAndUpdate({ id: req.params.id }, { $set: { task: req.body.task } }, { new: true },
function(err, doc) {
if(!err){
res.json( {success: true } )
}
});
}).catch(err => res.status(404).json( {success: false} ));