无法使用bodyParser获取请求正文

4

我正在构建一个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}`);

  });
});

在客户端,我这样进行调用:

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

当我试图记录JSON.stringify(inputData)时,对象已正确转换为JSON字符串, 但当我尝试从服务器端记录_req.body时,它始终是{}。 请帮助我找出我做错了什么。
1个回答

8

尝试在头部中设置JSON:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接