【问题标题】:How to access POST request body in Express server with TypeScript and Webpack?如何使用 TypeScript 和 Webpack 访问 Express 服务器中的 POST 请求正文?
【发布时间】:2021-12-09 21:33:21
【问题描述】:

我使用基于 Webpack 的入门节点和 Express Web 服务器,使用 babel-loader 和 ts-loader。

接下来是部分代码:

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..."));

当对路由http://localhost:5000 执行POST 请求时,它会激活index.ts 文件中的路由,其中​​放置了命令console.log(req.body); 结果,我在终端中看到了空对象-{}

请求是由Postman 程序发出的,如屏幕截图所示:

和这样的请求是一样的:

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

感谢关注!

【问题讨论】:

  • 通过从邮递员屏幕截图的最右侧列表中选择,尝试使用原始 JSON 发送相同的请求

标签: javascript typescript express webpack babeljs


【解决方案1】:

我建议你查看this question here,那里有一个很好的讨论,你可能会发现一些有用的东西。

确保你有 Content-Type: application/json 设置在标题中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2015-03-20
    • 2022-12-03
    相关资源
    最近更新 更多