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!