Search code examples
node.jsfsfetch-apibody-parser

The POST request I have is always undefined, and can't read my JSON object


So I am building some Blog software with FS and Express, with BodyParser. Anyhow, when I send a POST request (using the Fetch API)

When I enter the correct password (as an .env variable in config.js file) it says that it's incorrect, and the guess was undefined. I've tried quite a lot, but nothing works. (My undo() function removes symbols and returns the output.)

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ strict:false }));
app.post("/newpost", (req, res) => {
  if (req.body.password == config.PASSWORD) {
    fs.writeFile("/blog/" + undo(req.body.name) + ".md", req.body.context, (err) => {
      console.log("Probably made file. Error: " + err);
    });
  } else {
    console.error("Someone tried guessing and making a blog on your Blog. Stay safe. Their guess was " + req.body.password + ".");
  }
});

And here is the function for adding a new blog:

var xv=prompt("Enter the password.");
var ob = {password: xv, name: document.getElementById("title").innerText, context: document.getElementById("context").innerHTML};
fetch("/newpost",{method:"POST", body:JSON.stringify(ob)});

Solution

  • As you are converting to string, here-

    var xv=prompt("Enter the password.");
    var ob = {password: xv, name: document.getElementById("title").innerText, context: document.getElementById("context").innerHTML};
    fetch("/newpost",{method:"POST", body:JSON.stringify(ob)});
    

    You need to convert back to object here

    app.use(bodyParser.json({ strict:false }));
    app.post("/newpost", (req, res) => {
      req.body = JSON.parse(req.body);
      if (req.body.password == config.PASSWORD) {
        fs.writeFile("/blog/" + undo(req.body.name) + ".md", req.body.context, (err) => {
          console.log("Probably made file. Error: " + err);
        });
      } else {
        console.error("Someone tried guessing and making a blog on your Blog. Stay safe. Their guess was " + req.body.password + ".");
      }
    });```