无法让我的 POST 请求正常工作

时间:2021-01-04 21:26:47

标签: javascript json express post postman

我正在尝试向 mongo db 发出测试发布请求。在 Postman 中,我收到此错误:

{
    "success": false,
    "message": "Post validation failed: photo: Path `photo` is required., body: Path `body` is required., snippet: Path `snippet` is required., title: Path `title` is required."
}

This is what I have in Postman.

这是 Postman 的截图。

const postSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    snippet: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    photo: {
        type: String,
        required: true
    },
}, { timestamps: true });

const Post = mongoose.model('Post', postSchema);
module.exports = Post;

这是我的架构。

router.post("/add-story", upload.array('photo', 10), async(req, res) => {
  try{
    let post = new Post();
    Post.title = req.body.title;
    Post.description = req.body.description;
    Post.photo = req.body.photo;
    Post.snippet = req.body.snippet;

    await post.save();

    res.json({
      status: true,
      message: "Successfully saved."
    });
  } catch(err) {
    res.status(500).json({
      success: false,
      message: err.message
    });
  }
});

这是 POST 请求。

我尝试关闭“required: true”,请求成功通过,并在我的数据库中创建了一个空条目。

3 个答案:

答案 0 :(得分:0)

尝试将您的体型从 x-www-form-urlencoded 更改为 form-data,看看是否有效:

如下图所示:
enter image description here

答案 1 :(得分:0)

我认为您正在尝试发布多张照片,最多 10 张照片?您的 photo 上的 postSchema 属性应该是一个数组。你应该设置它

// ...
photo: {
    type: [String], // have multiple images
    required: true
}, 

路线 /add-story 会是这样,

router.post('/add-story', upload.array('photo', 10), async (req, res) => {
    const photoPath = [];
    req.files.forEach(file => {
        photoPath.push(file.path);
    });

    req.body.post = photoPath;
    const post = new Post(req.body);
    try {
        await post.save();
        return res.json({
            status: true,
            message: "Successfully saved."
        });
    } catch (err) {
        return res.status(500).json({ success: false, message: err.message });
    }
});

照片数组来自请求的二进制数据,可以作为 req.files 访问。

答案 2 :(得分:0)

最后是拼写错误。

我有:

let post = new Post();
    Post.title = req.body.title;
    Post.description = req.body.description;
    Post.photo = req.body.photo;
    Post.body = req.body.body;
    Post.snippet = req.body.snippet;

但需要:

let post = new Post();
    post.title = req.body.title;
    post.description = req.body.description;
    post.photo = req.body.photo;
    post.body = req.body.body;
    post.snippet = req.body.snippet;