Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can not get request body using bodyParser

I'm building a NextJS React Application. In my server/index.tsx, I get:

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}`);

  });
});

and on client side I'm making calls like this:

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

when I tried to log JSON.stringify(inputData), the object is correctly changed to JSON string, but when I tried to log _req.body from server side, it's always {}

please help me figure out what I'm doing wrong.

like image 371
stacy Avatar asked Sep 04 '25 16:09

stacy


1 Answers

Try it in setting json in headers :

await fetch('http://localhost:9000/api/client',{
    method: 'POST',
    body: JSON.stringify(inputData),
    headers: {
         'Content-Type': 'application/json'
    },
like image 87
BENARD Patrick Avatar answered Sep 07 '25 18:09

BENARD Patrick