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

How to create a SSL certificate for localhost development in NodeJS/Express/TypeScript

Generate the required SSH keys. In the process we’ll be asked for a few questions about the organisation etc.

openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
openssl rsa -in keytmp.pem -out key.pem

Now we have our certificates ready for use.

In our index.ts:

import * as https from "https";
import * as fs from "fs";
import * as express from "express";

// expressJS options
const httpsOptions = {
  key: fs.readFileSync("/Users/mimo/.openssl/key.pem"),
  cert: fs.readFileSync("/Users/mimo/.openssl//cert.pem"),
  requestCert: false,
  rejectUnauthorized: false
};

const server = https.createServer(httpsOptions, app).listen(app.get("port"), function() {
  console.log("server started at port 3000");
});