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

857
Views
Express post not receive JSON data [close]

I have this problem because I am sending data via JavaScript using XMLHttpRequest but not receiving it in node.js express post method. I don't know what I'm doing wrong.

My script - funcion form execute on window load

function form() {
  const btn = document.getElementById("save-data");
  let currentPage = window.location.href.split("/").at(-1);

  function sendData(data) {
    const XHR = new XMLHttpRequest();
    XHR.open("POST", window.location.href);
    XHR.setRequestHeader("Content-Type", "application/json");
    console.log(data); // I get right data
    XHR.send(data);
  }

  btn.addEventListener("click", () => {
    switch (currentPage) {
      case "settings":
        const prefix = document.getElementById("prefix").value;
        let buttonState = document.getElementById("module-state");

        if (buttonState.hasAttribute("enable")) {
          buttonState = "enable";
        } else {
          buttonState = "disable";
        }

        sendData({
          prefix: prefix,
          buttonState: buttonState,
          announcements: {
            giveawayChannelID: 123,
            updateChannelID: 123,
          },
        });
    }
  });
}

My Node.js code

router.post('/:id/settings', (req, res) => {
   console.log(req.body) // {}
})

Pleas help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to install body-parser package by NPM, and require it in your code

Try

npm i body-parser

Then in your main node script, require it

const bodyParser = require('body-parser');

after that, you should set it as a middleware for express

app.use(bodyParser.json()); //Handles JSON requests
app.use(bodyParser.urlencoded({ extended: false })); //Handles normal post requests

after these steps, you can access values like req.body.value

about 4 years ago · Juan Pablo Isaza 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!