【问题标题】:Put request with Express and Mongo DB使用 Express 和 Mongodb 提出请求
【发布时间】:2020-06-15 09:30:59
【问题描述】:

我正在构建一个简单的反应列表应用程序,它使用 express 和 mongoDB 来获取所有 CRUD 操作的句柄。到目前为止,我有 GET、POST、DELETE,工作得很好,但我似乎无法让 PUT 正常工作。 当我通过 Insomnia 尝试 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;

【问题讨论】:

    标签: reactjs express mongoose put


    【解决方案1】:

    你忘记在你的 put 路由中发送响应

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

    【讨论】:

    • 谢谢尼桑!完全忽略了这一点。
    猜你喜欢
    • 2017-09-16
    • 2017-05-24
    • 2021-07-25
    • 1970-01-01
    • 2019-07-03
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多