无法使用 bodyParser 获取请求正文

sta*_*acy 4 fetch express typescript body-parser next.js

我正在构建一个 NextJS React 应用程序。在我的 server/index.tsx 中,我得到:

import next from 'next';
import express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import { parse } from 'url';
import { createServer as createHttpServer } from 'http';
import { ParsedUrlQuery } from 'querystring';

const port = 9000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({ dev });

const handleNextRequests = nextApp.getRequestHandler();

/**
 * Compression setup
 */
const shouldCompress = (
  req: express.Request,
  res: express.Response
): boolean => {
  // don't compress responses explicitly asking not
  if (req.headers['x-no-compression']) {
    return false;
  }

  // use compression filter function
  return compression.filter(req, res);
};

nextApp.prepare().then(() => {
  /**
   * Express application setup
   */
  const expressApp = express();

  // setup compression in express
  expressApp.use(compression({ filter: shouldCompress }));
  expressApp.use(bodyParser.urlencoded({ extended: true }));
  expressApp.use(bodyParser.json());
  expressApp.use(bodyParser.raw());
  expressApp.use(express.json()); 

  ...

  expressApp.post("/api/client", async (_req: express.Request, _res: express.Response) => {
    
    console.log(_req.body)
    _res.send(_req.body)
  });


  // fallback all requests to next request handler
  expressApp.all('*', (req: express.Request, res: express.Response) => {
    return handleNextRequests(req, res);
  });

  createHttpServer(expressApp).listen(port, async (err?: any) => {
    if (err) {
      throw err;
    }
    console.log(`HTTP server listening on port: ${port}`);

  });
});
Run Code Online (Sandbox Code Playgroud)

在客户端,我正在拨打这样的电话:

console.log('json: '+JSON.stringify(inputData))
    await fetch('http://localhost:9000/api/client',{
        method: 'POST',
        body: JSON.stringify(inputData)
    }).then(res => res.json());
Run Code Online (Sandbox Code Playgroud)

当我尝试记录 JSON.stringify(inputData) 时,对象已正确更改为 JSON 字符串,但是当我尝试从服务器端记录 _req.body 时,它始终是 {}

请帮我弄清楚我做错了什么。

Pim*_*Web 8

尝试在 headers 中设置 json :

await fetch('http://localhost:9000/api/client',{
    method: 'POST',
    body: JSON.stringify(inputData),
    headers: {
         'Content-Type': 'application/json'
    },
Run Code Online (Sandbox Code Playgroud)