我正在构建一个简单的反应列表应用程序,该应用程序使用express和mongoDB来获取所有CRUD操作的句柄。到目前为止,我的GET,POST,DELETE工作正常,但PUT似乎无法正常运行。当我通过失眠尝试PUT请求时,出现以下错误“错误:从对等方接收数据时失败”
模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const listItemSchema = new Schema({
itemname: { type: String, required: true, unique: true },
category: { type: String, required: true, unique: true },
}, {
timestamps: true,
});
const ListItem = mongoose.model('ListItem', listItemSchema);
module.exports = ListItem;
路线
const router = require('express').Router();
let ListItem = require('../models/list.model');
router.get('/', async (req, res) => {
try {
const list = await ListItem.find();
res.json(list);
} catch(err) {
console.error(err.message);
res.send(400).send('Server Error');
}
});
router.get('/:id', async (req, res) => {
try {
const item = await ListItem.findById(req.params.id);
res.json(item);
} catch(err) {
console.error(err.message);
res.send(400).send('Server Error');
}
});
router.post('/addlistitem', async (req, res) => {
try {
const { itemname, category } = await req.body;
const newListItem = new ListItem({
itemname,
category
});
await newListItem.save()
res.json('ListItem added!')
} catch(err) {
console.error(err.message);
res.status(500).json('Server Error');
}
});
router.delete('/:id', async (req, res) => {
try {
await ListItem.findByIdAndDelete(req.params.id);
res.json(' Item deleted.');
} catch(err) {
res.status(400).json('Error: ' + err);
}
});
router.put('/:id', async (req, res) => {
try {
await ListItem.findByIdAndUpdate(req.params.id, {
itemname: req.body.itemname,
category: req.body.category
});
} catch(err) {
console.error(err.message);
res.send(400).send('Server Error');
}
});
module.exports = router;
您忘了在推入路线中发送回复
router.put('/:id', async (req, res) => {
try {
await ListItem.findByIdAndUpdate(req.params.id, {
itemname: req.body.itemname,
category: req.body.category
});
// Send response in here
res.send('Item Updated!');
} catch(err) {
console.error(err.message);
res.send(400).send('Server Error');
}
});