when i first log req.body and req.file it is defined at first console.log but when i try to access them it is undefined and i absolutely don't know why.
i am building a small social network so when i post an image with some text the post is saved in mongo even with this error
here is the errors:
TypeError: Cannot read properties of undefined (reading 'filename')
at exports.createPost (/Users/curlynux/Documents/groupomania-p7/backend/api/controllers/postController.js:12:26)
but after this error, req.file is defined and work well ... why after ? after the error:
{
fieldname: 'image',
originalname: '73423630_448993115731641_5411606821110292030_n.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'images',
filename: '73423630_448993115731641_5411606821110292030_n.jpg1663242018229.jpeg',
path: 'images/73423630_448993115731641_5411606821110292030_n.jpg1663242018229.jpeg',
size: 41437
}
73423630_448993115731641_5411606821110292030_n.jpg1663242018229.jpeg
POST /post 201 74.811 ms - 26
req.body is defined firstly:
{
login: 'login',
imageUrl: 'string',
post_text: 'test',
like: '0',
disLike: '0'
}
but undefined after ?: [Object: null prototype] {}
my postController.js:
const express = require("express");
const app = express();
const Post = require("../models/postModel");
app.use(express.json())
app.use(express.urlencoded({extended: false}))
exports.createPost = (req, res) =>
{
console.log(req.body);
console.log(req.file);
console.log(req.file.filename);
const post = new Post({post: {
login: req.body.login,
imageUrl: `${req.protocol}://${req.get("host")}/images/${req.file.filename}`,
post_text: req.body.post_text,
like: req.body.like,
disLike: req.body.disLike
}})
post.save().then(() => res.status(201).json({message: "post created"}))
}
chrome error: POST http://localhost:8080/post 500 (Internal Server Error) home.jsx:69
the corresponding code for the chrome error:
try
{
fetch("http://localhost:8080/post",
{
method: "POST",
mode: "cors",
headers: postHeader,
body: JSON.stringify(postData)
}).then(response => console.log(response))
.then(data => console.log(data))
} catch (error)
{console.error(error)}