Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
I am getting undefined from express. Why req.body is showing empty object {}?

This is noob question but I am new to it. Req.body is undefined. I tried without body-

parser and with body-parser, I keep getting the same result I tried all solutions

available in StackOverflow but I keep getting the same result.

This is my client side code:

document.addEventListener("DOMContentLoaded", () => {
            document.getElementById('send').addEventListener('click', (e) => {
                var message = { name: document.getElementById('name').value, message: document.getElementById('message').value }
                postMessages(message)
            })
            getMessages()

        });
        function addMessages(message) {
            const ele = document.getElementById('messages')
            const h4 = document.createElement('h4')
            const p = document.createElement('p')
            h4.textContent = `${message.name}`
            p.textContent = `${message.message}`
            ele.append(h4, p)
        }
        function postMessages(message) {
            const Url = "http://localhost:3000/messages"
            fetch(Url, {
                method: 'POST',
                body: message,
            })
        }

And this is my NodeJs code:

var express = require('express')
var bodyParser = require('body-parser')
var app = express()

app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
var messages = [
    { name: "Tim", message: "Hi" },
    { name: "Jane", message: "Hello" }
]
app.post('/messages', (req, res) => {
    console.log(req.body)
    messages.push(req.body)
    res.sendStatus(200)
})

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to change your fetch function and first JSON.stringify your message and then add correct headers:

function postMessages(message) {
        const Url = "http://localhost:3000/messages"
        fetch(Url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(message),
        })
    }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!