How To Post Data With Fetch API To An ExpressJS API Endpoint

Let’s start by assuming that our app is set up and express is running.

We need to have a route to

app.post("/capture", homeController.getPostRequests);

Let’s define our controller under src/controllers/homeController.ts:

import { Request, Response } from "express";

export let getPostRequests = (req: Request, res: Response) => {
  console.log(req.body); // Data coming from the frontend
  res.json({ "message": "got it", other: [ 1, 2, 3 ]  });
};

And import it in server.ts:

import * as homeController from "./controllers/homeController";

In the frontend we’ll have:

fetch("https://localhost:3000/capture",
{
  method: "POST",
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ user: "mimo", "email": "hello@example.com", "more": [ "a", "b", "c" ] })
})
.then(res => res.json() )
.then(data => { console.log(data) }) // Logs data coming from server