Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader.

Let's take a look at some key portions of the code:

webpack-config.js:

const path = require("path");
const nodeExternals = require("webpack-node-externals");
const Dotenv = require("dotenv-webpack");
require("dotenv/config");

const OUTPUT_FOLDER = process.env.OUTPUT_FOLDER;

module.exports = {
  mode: "development",
  watch: true,
  node: {
    __dirname: false,
  },
  externalsPresets: { node: true },
  entry: "./index.ts",
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, OUTPUT_FOLDER),
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: 'ts-loader',
      },
    ],
  },
  plugins: [new Dotenv()],
};

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "output",
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "allowJs": true,
    "moduleResolution": "node"
  },
  "include": ["src/**/*.ts", "test/**/*.ts"],
  "exclude": ["node_modules"]
}

index.ts:

import * as express from 'express';    
const app = express();    
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post("/", (req, res) => {
  console.log(req.body);
  res.json("OK");
});

app.listen(5000, () => console.log("Server started at 5000..."));

When sending a POST request to http://localhost:5000, it triggers the route defined in index.ts, where console.log(req.body); is called. However, the terminal displays an empty object - {}.

The request is generated using the Postman program, as shown in the following screenshot:

https://i.stack.imgur.com/AItoz.jpg

This request is equivalent to the following:

axios.post("http://localhost:5000/", {
  _id: "12345",
  name: "Sim-sim open",
});

Thank you for your attention!

Answer №1

It would be beneficial to review this specific question for some valuable insight and potentially helpful solutions.

Ensure that the header includes Content-Type: application/json.

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

Use joi to validate the entire request object

In order to ensure the validity of request input before calling the controller logic, I developed a middleware for that purpose. Let's suppose we have a route for "getting user by id". const usersController = require('../controllers/users.js&ap ...

Enhanced VS code typings for Nuxt injected properties

My approach to injecting properties into the Nuxt TS context is as follows: ~/plugins/services.ts import Vue from 'vue'; import { errorService } from '~/services/error'; import { Plugin } from '@nuxt/types' const services: Pl ...

What if we had webpack disregard certain syntactic enhancements?

For instance: using optional chaining The application I'm working on is strictly for internal use, and it's specifically optimized for the latest Chrome browser. This means I can take advantage of syntactic sugar without needing to compile it, w ...

Tips for utilizing JavaScript to engage with a Cisco call manager

Our team is currently working on an IVR web application built with node js. I am wondering if it is feasible to integrate with the cisco unified call manager directly through node js in our web application? ...

How can I send a curl request to node.js server but receive a 200 JSON response from server.js?

I have set up a notification system on node.js and I am trying to push notifications to it using curl in PHP. However, when I use curl in either terminal or PHP, it doesn't return anything but the notification is successfully pushed. How can I modify ...

combine two arrays of observations into a unified array of observations

One challenge I am facing is merging two Observable arrays in Angular without using the subscribe method. How can this be achieved? My approach so far has been as follows: this.similarIdeasObservable$.pipe(concat(this.ideaService.getSimilarIdeas(this.id ...

Using AJAX to pass post variables

Here is a link I have: <a class="tag" wi_id="3042" wl_id="3693" for_user_id="441" href="#a"> This link triggers an ajax call. $(".tag").click(function() { var for_user_id = $(this).attr("for_user_id"); var wl_id = $(this).attr("wl_ ...

Iterate over a collection of HTML elements to assign a specific class to one element and a different class to the remaining elements

Forgive me if this is a silly question, but I have a function named selectFace(face); The idea is that when an item is clicked, it should add one class to that item and another class to all the other items. This is what I currently have: HTML <div c ...

A step-by-step guide on updating a deprecated typings package manually

Currently, I am developing a NodeJS application using TypeScript and incorporating numerous Node packages. However, not all of these packages come with TypeScript definitions, so Typings is utilized to obtain separate definition files. During the deployme ...

An AJAX request will only occur if there is an alert triggered on a particular computer

Here's an interesting issue I encountered with my company's CMS newsletter system. It seems that the AJAX call to send an email works flawlessly in all modern browsers and operating systems, except for one client. This particular client is using ...

Effortless 'rotational' script

I am currently developing a HTML5 Canvas game with the help of JavaScript. My aim is to create an object that smoothly transitions to a specific direction. The direction is being stored as a variable and calculated in radians. Here's how the code op ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

The JSON file gets emptied every time I refresh the page repeatedly

I am encountering an issue where my JSON file gets cleared if I restart the page quickly after using the fs module to read/write it. The JSON data is read at the beginning of the page like this: let preferencesJSON; try { preferencesJSON = fs.readFile ...

Having trouble with VSCode/tsconfig path configurations, as the files are being fetched but still receiving a "Module not found" error in the editor

Since I began working on this project, I've been encountering a peculiar issue. When importing modules and files in my Angular components/classes using import, I face an error in VSCode when the paths use the base path symbol @. Strangely enough, desp ...

Connecting RxJS Observables with HTTP requests in Angular 2 using TypeScript

Currently on the journey of teaching myself Angular2 and TypeScript after enjoying 4 years of working with AngularJS 1.*. It's been challenging, but I know that breakthrough moment is just around the corner. In my practice app, I've created a ser ...

What is the best method for transforming a base64 encoded string into a base64 formatted PDF string?

Could someone please help me with a problem I'm facing? I am utilizing an AngularJS .pdf viewer that displays documents in a modal using base64. Everything works smoothly when the base64 is generated from a .pdf file. The backend (Java) generates th ...

Unable to retrieve session data from a different route

Currently utilizing client-sessions with the following code snippet: app.post("/login", (req, res)=>{ if (!req.session.activeUser){ User.findOne({username:req.body.username}).then(doc=>{ req.session.activeUser = req.body.use ...

The React-widgets DateTimePicker is malfunctioning and displaying an error stating that it cannot assign to the type of 'Readonly<DateTimePickerProps>'

Hello there! I am a newcomer to TypeScript and I am facing difficulty in understanding an error. Any help regarding this will be greatly appreciated. I have tried searching for solutions online and even attempted changing the version, but I am unsure of wh ...

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

What is the best way to verify the presence of a value in MongoDB using Axios?

I am currently learning MERN stack development and working on a practice app that involves user login/registration functionalities. At the moment, my Node server and MongoDB are up and running smoothly. I have successfully implemented features such as regi ...