Home > Enterprise >  Post req.body is always empty object
Post req.body is always empty object

Time:11-01

I'm using Typescript Fetch wrapper to do post and get requests and getting empty object on post(get works fine) (Before I used Vanilla Js and all worked fine) Nodejs:

const express = require('express');
const fs = require('fs');

const app = express();
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});
app.use(express.json());

app.post('/login', (req, res) => {
  let isLogged = login(req.body);
  console.log(req.body);

  res.status(200).json(isLogged);
});

My Typescript fetch Wrapper:

async function fetchWrapper<T>(path: string, config: RequestInit): Promise<T> {
  const request = new Request(path, config);
  const response = await fetch(request);
  if (!response.ok) {
    throw new Error(
      `name: ${response.status}, message: ${response.statusText}`
    );
  }
  // return empty object
  return response.json().catch(() => ({}));
}
   
export async function post<T, U>(
  path: string,
  body: T,
  config?: RequestInit
): Promise<U> {
  const init = { method: 'post', body: JSON.stringify(body), ...config };
  return await fetchWrapper<U>(path, init);
}

my post request:

    const res = await fetch.post(`${url}/login`, {
      body: inputData,
      headers: { 'Content-Type': 'application/json' },
    });

input data is not empty

CodePudding user response:

The problem here that you are using wrong Content-Type header value. express.json parses application/json content type, while you are sending application/x-www-form-urlencoded. The solution is either to change the content-type you are sending, or add another middleware like bodyparser to parse application/x-www-form-urlencoded body.

  • Related