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.