The Express API controller is unexpectedly receiving empty strings

I am encountering an issue where my API is receiving an empty string instead of the expected data when I send post requests with a single string in the body.

Below are the client, server, and controller components involved:

Function call (client):

 const response = await api.uploadImg("image");

Axios request (client):

const uploadImg = async (image: string) => {
  const response = await axios.post(`${apiBaseURL}/api/image`, image);
  return response.data;
};

Router (server):

import { Router } from "express";
import controller from "../controllers/image";

const router = Router();

router.post("/", controller.upload);

export default router;

Controller (server):

import { Request, Response } from "express";

const upload = async (req: Request, res: Response) => {
  res.json(req.body)
};

export default { upload };

The unexpected response after sending the string "image" is:

{image: ''}

It's puzzling that this route, designed to receive base64 image strings for uploading to Cloudinary, always receives an empty string. To troubleshoot, I updated the controller to simply return the request body for testing purposes.

Full Express server setup:

import express from "express";
import morgan from "morgan";
import cors from "cors";
// Util
import config from "./config";
import connectMongo from "./config/mongo";
import connectCloudinary from "./config/cloudinary";
// Routes
import indexRoutes from "./routes";
import userRoutes from "./routes/user";
import postRoutes from "./routes/post";
import imageRoutes from "./routes/image";

const server = express();

server.listen(config.server.port, () => {
  console.log("Server running on port:", config.server.port);

  // Logging during development
  if (config.server.env === "development") server.use(morgan("dev"));

  // Parse requests
  server.use(express.urlencoded({ extended: true, limit: "50mb" }));
  server.use(express.json({ limit: "50mb" });

  // Connect to the database
  connectMongo();

  // Connect Cloudinary for image uploads
  connectCloudinary();

  // Cross-origin routing
  server.use(
    cors({
      origin: config.client.url,
    })
  );

  // Routing
  server.use("/", indexRoutes);
  server.use("/api/users", userRoutes);
  server.use("/api/posts", postRoutes);
  server.use("/api/image", imageRoutes);
});

Link to GitHub repo for back-end here.

Answer №1

There was an issue with the axios call:

const uploadImg = async (image: string) => {
  const response = await axios.post(`${apiBaseURL}/api/image`, image);
  return response.data;
};

Instead of passing the string variable image, it needed to be wrapped in curly braces to convert it into an object. So, the corrected code is:

const uploadImg = async (image: string) => {
  const response = await axios.post(`${apiBaseURL}/api/image`, {image});
  return response.data;
};

This change resolves the issue and now the function works perfectly.

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

Express server experiencing a backlog of POST requests after receiving six requests from the same browser, resulting in unexpected or unusual behavior

My application is experiencing delays in processing post requests when multiple requests are sent within a short timeframe. This results in unexpected behavior. For instance: app.options('/',cors({origin: "http://localhost:5050"})); ap ...

The Heroku deployment is unsuccessful due to the inability to locate the configuration module

I keep encountering this issue when checking my Heroku logs: Error: Module './config/keys' cannot be found. This particular piece of code is from my index.js file: const keys = require('./config/keys'); The keys.js file is located wi ...

Refresh the Angular view only when there are changes to the object's properties

I have a situation where I am fetching data every 15 seconds from my web API in my Angular application. This continuous polling is causing the Angular Material expansion panel to reset to its default position, resulting in a slow website performance and in ...

What are the steps to set up Redis Store in my production environment?

I am currently in the process of setting up Redis as a session store, but for some reason it's not functioning properly. I have integrated passport.js and express-flash, however when I attempt to run the current Redis setup, it fails to work: var ses ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Event for changing Ionic 2 page

Is there a way to execute code every time the page changes without adding an ngOnDestroy method to every page in Ionic 2? Instead of using Ionic 2 page lifecycle hooks like ionViewDidUnload, is there a simpler solution by adding a single method to the mai ...

Exploring the archives of PubNub within Angular5

I've been working on integrating PubNub history into my web app, but I'm currently only able to view it in the console. Here's what I have so far: pubnub.history( { channel: 'jChannel', reverse: false, ...

Error: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

Calling a typed function with conditional types in Typescript from within another function

In my attempt to create a conditional-type function, I stumbled upon this question on Stack Overflow. Unfortunately, it seems that the approach doesn't work well with default values (regardless of where the default value is placed). Following the advi ...

Unlocking the power of the enhanced Twitter API in node.js: Understanding the necessity of the 'event' field

I've encountered an error while attempting to send direct messages using the Twitter API. message: 'event: field is required', code: 214, allErrors: [ { code: 214, message: 'event: field is required' } ], twitterReply: { err ...

The formControl value is not being shown on the display

I am facing an issue with a form that has multiple fields created using formGroup and formControlName. The challenge arises when I launch the application and need to retrieve data from the back end to display it on the view. The specific problem I'm ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

What is the process for initiating a local Lambda edge viewer request?

Is there a way to run aws cloudfront lambda edge functions locally and simulate the event in order to observe the response from one of the four functions? I made modifications to the viewerRequest function of lambdaEdge, but I'm wondering if there is ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

I am looking to retrieve products based on category alone, category and model together, or simply obtain all products in one go. At the moment, I am utilizing three distinct endpoints

I have 3 endpoints on my backend that fetch products based on certain criteria. I'm considering whether to refactor the logic and combine them into a single endpoint/function. Currently, my routes are structured as follows: router.get('/products& ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Testing NextJS App Router API routes with Jest: A comprehensive guide

Looking to test a basic API route: File ./src/app/api/name import { NextResponse } from 'next/server'; export async function GET() { const name = process.env.NAME; return NextResponse.json({ name, }); } Attempting to test ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...