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

Encountered an issue with the property 'push' not being defined

Here's the schema for my mongoose model in JavaScript: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CartSchema = new Schema({ userID: String, items: [{ itemID: String, quantity: Number }] }); modul ...

Using TypeScript with React's forwardRef

Here's my code where I have utilized React's forwardRef: interface PropsDummy {} const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => { console.log(ref.current); } However, I'm encountering a TypeScript e ...

Decoding JSON data into a multidimensional array

Upon receiving data from an API, the following information is retrieved: { "isVacation":"1", "date":"25.12.2014", "occasion":"1. Christmas Day", "locations":["BW","BY","BE","BB","HB","HH","HE","MV","NI","NW","RP","SL","SN","ST","SH","T ...

Enhance your Fastify routes by incorporating Swagger documentation along with specific tags and descriptions

Currently, I am utilizing fastify 3.28.0 in conjunction with the fastify-swagger plugin and typescript 4.6.2. My goal is to include tags, descriptions, and summaries for each route. As per the documentation found here, it should be possible to add descrip ...

Encountering SequelizeConnectionRefusedError while trying to connect to Docker container at localhost on port 3306

Trying to launch my nodejs application using a docker container, but encountering issues. The credentials appear to be correct when checked with the console. Also, connecting directly with the same credentials in sequel pro works fine. However, upon starti ...

What could be preventing the jQuery from showing the JSON response?

I am having an issue with a jQuery script that is supposed to pull a quote from an API in JSON format and display it on the page. However, for some reason, I am unable to retrieve data from the API. Can you help me figure out what is wrong here? Thank yo ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Using Class as a Parameter

I recently started using TypeScript and encountered an implementation issue. I'm working on a class that takes another class as an argument. The challenge is that it can be any class, but I want to define certain possible class properties or methods. ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Node.js Express session expiration caused by code changes

Greetings, I am currently working on a login application using Node.js (express framework) and MySQL. To manage sessions, I am utilizing express-session. However, I have encountered an issue where my session expires quickly or gets cleared when there is a ...

What are the distinctions between generic and discriminated types?

Hi there, I've been thinking of an idea but I'm not sure how to implement it or if it's even possible. Is there a way to create a type SomeType where the first property can be any value from the set T, but the second property cannot be the ...

Create the next app with updated files by rebuilding it while utilizing express as the server

I'm currently utilizing the combination of Next.js and Express.js in my project. In this setup, Express handles all the routing tasks instead of Next.js. For a smoother development experience, I require a process where whenever a file is modified, Ne ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

Angular 14: Deleting an item from a FormArray triggers unintended form submission due to Angular animation

After beginning to create animations for my app, I observed that deleting an element from a FormArray triggers a form submission. Custom form controls were developed using ControlValueAccessor, and certain FormGroups are passed through @Inputs. The animati ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

What is the best way to utilize an HTML form for updating a database entry using the "patch" method?

I have been attempting to update documents in my mongoDB database using JavaScript. I understand that forms typically only support post/get methods, which has limitations. Therefore, I am looking for an alternative method to successfully update the documen ...

Issue: Module "mongodb" could not be found when using webpack and typescript

I am encountering an issue while trying to use mongoose with webpack. Even though I have installed it as a dependency, when attempting to utilize the mongoose object and execute commands, it gives me an error stating that it cannot find the "." Module. Thi ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Dealing with precompile array warning when utilizing a basic router in Angular 2

I am currently working on developing a straightforward router-based application in Angular2 using typescript. The version of Angular2 I am using is 2.0.0-rc.4, and the router version is 3.0.0-beta.1 Here is my Routes configuration- App.routes.ts import ...

Enhancing data validation and converting strings to dates with Nest.js - DTO approach

Anticipating the upcoming request to adhere to the ISO 8601 standard timestamp format, something similar to "2023-12-04T15:30:00Z" (typically embedded as a string within JSON data that needs conversion to a JavaScript Date object). This is my Data Transfe ...