Error in Express.js App: Attempting to access properties of an undefined object (specifically 'transfer-encoding')

Currently, I am developing a blogging app API using express and MongoDB.

In my project, I want to include an image for each blog post. However, as someone who is new to express, I encountered a specific issue that has been puzzling me.

The error message I received reads: Cannot read properties of undefined (reading 'transfer-encoding'

Below is the code snippet from the post controller:

const asyncHandler = require("express-async-handler");

const imageModel = require("../models/imageModel");

const User = require("../models/userModel");
const Post = require("../models/postModel");

//  storage
const Storage = multer.diskStorage({
  destination: "storage",
  filename: (res, req, file, cb) => {
    cb(null, Date.now() + file.originalname);
  },
});

const upload = multer({
  storage: Storage,
}).single("img");

// @desc    Create a new post
// @route   POST /api/posts/
// @access  Private
const createPost = asyncHandler(async (res, req) => {
  let img;

  upload(req, res, async function (err) {
    if (err) {
      res.status(400);
      throw new Error("Error uploading images.");
    }
    const newImage = await new imageModel({
      img: {
        data: req.file.filename,
        contentType: "image/png",
      },
    });
    newImage.save().then(console.log("Successfully uploaded"));
    img = newImage;
  });

  console.log(img);

  const { title, description, categories, nacCompatible, downloadURL } =
    req.body;

  if (!title || !description || !categories || !downloadURL) {
    res.status(400);
    throw new Error("Please add all the required fields.");
  }

  // Get user using the id in the JWT
  const user = await User.findById(req.user.id);

  if (!user) {
    res.status(401);
    throw new Error("User not found");
  }

  const post = await Post.create({
    title,
    description,
    img,
    categories,
    nacCompatible,
    downloadURL,
    user: req.user._id,
    status: "new",
  });

  res.status(201).json(post);
});

I also included

const multer = require("multer");
at the top of the controller.

Prior to implementing the image upload feature, the create post function worked without any issues.

Answer №1

The following code snippet: "createPost = asyncHandler(async (res, req)"

There appears to be a mistake with the order of req and res

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

Extracting a specific variable value from a response by sending a request with CURL command and manipulating the data using JavaScript

Here is my Curl request: curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \ -X GET "https://api-cloud.browserstack.com/app-automate/sessions/22dbfb187486090d974a11ac91t65722988e0705.json" This is the Response I received: { "automati ...

Exploring the functionalities of JavaScript methods and nested components within Vue.js

Learning Vue.js has been an interesting experience for me. However, I am facing challenges with methods and child elements in the library. It seems like there is something simple that I am overlooking. In my current project, I have list items rendered on ...

Using the Mousetrap binding on a nuxt.js page may not be effective

Hey there! I'm trying to achieve a certain functionality where I want to redirect to a different page once a specific sequence is typed. Although I can see the message "It works" in my console, the redirection is not happening and instead, I am gettin ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

Retrieve the unique identifier of a div using JavaScript/jQuery

I am faced with a situation where I have two sets of divs structured as follows: First Div <div class="carousel"> <div class="item active" id="ZS125-48A">...</div> <div class="item" id="FFKG-34">...</div> <div cl ...

Encountering an issue while attempting to locate an already existing product in the localStorage using JavaScript

I'm currently working on incorporating a cart system using localStorage and have provided the codes below. Can someone help me understand how to accomplish this? const data = { description: "Cum sociis natoque", mediaUrl: "/prod ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

I rely on Grunt to manage my Angular 1 app, along with grunt-connect to host the website. However, when I refresh the page, there is no fallback mechanism in place, resulting in a 404 error and

Currently, I am utilizing Grunt to manage my angular 1 application and grunt-connect to serve the website. However, I have encountered an issue where on refresh, there is no fallback mechanism in place which results in a 404 error and a blank white screen. ...

Exploring the framework persistence options with a combination of Openshift, MongoDB, and JPA

Currently developing a project that involves utilizing restful web services alongside MongoDB. I'm considering incorporating JPA for database operations, but is Hibernate absolutely necessary? Would it be more beneficial to explore alternative lightwe ...

Determine if a specific date occurred at least one day ago using momentjs

Is there a way to determine if a specific date is at least one day (24 hours) in the past using momentjs? For example: const currentDate = moment() const isAtLeastOneDayAgo = currentDate.subtract(dateToVerify) > 1 // How can this be done? ...

How can I resolve a MySQL query error in Node.js that is throwing an undefined error?

There seems to be an issue with the second request returning undefined instead of showing the results. The expected behavior is that if the first request returns less than two lines, the second request should be executed. What could be causing this error ...

Ways to incorporate multiple catalogs into a query within MongoDB

Imagine I possess various records within distinct collections: Regarding vehicles: { "_id": 32534534, "color": "red", ... } Regarding properties: { "_id": 93867, "city": "Xanadu", ... } Is there a way to fetch the corresponding record within the peopl ...

The submission of the form is not functioning correctly when triggered by JavaScript using a button

My website was designed using a CSS/HTML framework that has been seamlessly integrated into an ASP.NET site. Within a ContentPlaceHolder, I have implemented a basic login form. The unique aspect is that I am utilizing the onclick event of an image to subm ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData(). According to the Nuxt.js documentation, asyncData() is triggered before loading page comp ...

Retrieving data from a database using PHP and presenting it in a loop for showcasing in JavaScript

I am currently working on a code and trying to achieve the following output: { title:"<?php echo $sender_fullname; ?>", mp3:"link", }, I want to display this in JavaScript using PHP. // Include database require_once "db.php"; // Get email ...