0

I'm having an issue where my req.body is always undefined when I do a POST. I'm using NodeJS, Express and BodyParser. Everything else I can find online says I need the include .json(), as below on the 1st line, but this didn't sort the issue. I've also tried with {extended: true} which also didn't help.

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(
    session({
        secret: 'my secret',
        resave: false,
        saveUninitialized: false,
        store: site
    })
);

If I run a line of code like req.body.text I'll just get undefined as the result. Does anyone know what my mistake might be?

Eind997
  • 169
  • 1
  • 1
  • 8
  • I think we'll need more details. Could you add: the route definition where you use `req.body`, the code you use to test it (i.e., send the POST request)? – Christian Fritz May 28 '22 at 21:15

2 Answers2

1

body parser is deprecated see https://stackoverflow.com/a/68127336/10772577.

Sending a post request to a route with 'Content-Type': 'application/json' should give you a body.

Example express route.

app.post('/api', function(request, response){
   console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

See https://expressjs.com/en/guide/routing.html

Example client request.

const response = await fetch('/api', {
    method: 'POST',
    body: JSON.stringify(object),
    headers: {
      'Content-Type': 'application/json'
    }
});

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Reed Hambrook
  • 86
  • 1
  • 3
  • Thanks Reed Hambrook, that seems to be working for most of the post requests but do you know if there's anything else I need to add for forms? I've added app.use(express_formidable()) but I get Error: Request aborted. – Eind997 May 29 '22 at 07:02
0
const app = express();
/* EXPRESS BODY PARSER */
app.use(express.json());
const myFunction(req,res) = async (req,res) => {
  const body = req.body;
}
Tyler2P
  • 2,182
  • 12
  • 17
  • 28
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 29 '22 at 10:40