I'm facing some problem when making a POST request. It works when I send raw data in JSON(application/json) format, but doesn't work when I send in form-data from Postman. I tried using multer but I am not sure if I did it right, so feel free to point that out too. Following is the screenshot of result from the Postman:
Here's the Mongoose Schema:
const mongoose = require('mongoose');
const ItemSchema = mongoose.Schema({
title:{
type: String,
required: [true,'Please enter a title for the item']
},
description:{
type: String,
required: [true,'Please enter a description for the item'],
},
image: {
type: String,
// required: [true, 'Please add an image for the item'],
}
});
// Uploading an image to the server and getting shareable url
ItemSchema.pre('save', async function (next) {
const file = this.image;
console.log(file);
});
module.exports = new mongoose.model('Items',ItemSchema);
Here's the post request from the controller:
exports.createItem = asyncHandler(async (req, res, next) => {
const item = await Item.create(req.body);
res.status(201).json({
success: true,
data: item
});
});
The routes are defined in a separate file as follows:
const express = require('express');
const multer = require('multer');
const { getItems, getItem, createItem, updateItem, deleteItem } = require('../controllers/itemController');
const router = express.Router({ mergeParams: true });
const upload = multer();
router
.route('/')
.get(getItems)
.post(createItem,upload.any());
router
.route('/:id')
.get(getItem)
.put(updateItem)
.delete(deleteItem);
module.exports = router;
