I’m making a POST request to create a blog post and I’m using formidable to upload an img for each post but I’m receiving a 400 error.
UPDATE: I’m now receiving an actual error:
Post validation failed: title: Cast to string failed for value "[ 'njk' ]" (type Array) at path "title", body: Cast to string failed for value "[ 'ugyjhvbhujb' ]" (type Array) at path "body", slug: Path `slug` is required.
console.log(formData) returns an object of strings in the frontend like:
{ title: "suyghb", body: "cguyasjbhxz"...}
but in the backend the values in fields aka formData are now arrays like:
{ body: [ 'ihubj' ], title: [ '87tugyh' ] }
why is this?
I tried setting
'Content-Type': 'application/json
but then I receive the error request entity too large.
posts.js (controllers)
export const create = (req, res) => {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded."
})
}
let post = new Post(fields)
if (files.photo) {
const photoFilePath = files.photo.map((file) => {
return file.filepath
})
}
const photoStr = photoFilePath.toString()
post.photo.data = fs.readFileSync(photoStr, 'utf-8')
post.photo.contentType = files.photo.type
}
post.save()
/• .then & .catch •/
Form Validation
const { body, validationResult } = require('express-validator');
exports.userSignupValidator = (req, res, next) => {
validationBodyRules = [
body('email', 'email is required').exists(),
body('password', 'password is required').exists(),
body('email', 'email is required').notEmpty(),
body('password', 'password is required').notEmpty()
]
checkRules = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
}
API request (client side)
export const createPost = (token, formData) => {
console.log(formData)
return fetch('http://localhost:8000/posts/new-post', {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: formData
})
.then(response => {
return response.json();
})
.catch(err => {
console.error(err);
});
};