Spencer K. Spencer K. - 1 month ago 15
Node.js Question

If there's an empty value for a key in JSON, send error status (AJAX, Node and Express)

Here's the flow I'm trying to achieve:


  • Use AJAX to send object to Node / Express server

  • Server-side,
    JSON.stringify
    the object in the request data

  • This is the important piece: If the value of the
    "task"
    key is empty / false (i.e. ""), send a response status client-side (e.g.
    res.sendStatus(403)
    )


    • Issue is that the server-side
      if
      block (indicated by a comment below) doesn't get run




Client-side AJAX post (main.js):

$.post("/add-tasks", userToDo);


userToDo object being sent server-side:

userToDo = {
task = string;
important = boolean;
urgent = boolean;
quadrant = int; // 1 - 4
}


Example stringified JSON:

{"task":"","important":"true","urgent":"false","quadrant":"2"}


Server-side JS (app.js) -- the important snippet is denoted by a comment:

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var fs = require("fs");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(function(req, res, next) {
console.log(`${req.method} request for '${req.url}' - ${JSON.stringify(req.body)}`);
next();
});

app.use(express.static("./public"));

app.post("/add-tasks", function(req, res) {

// ********* HERE **********
if ( !JSON.stringify(req.body["task"]) ) {
res.sendStatus(403);
} else {
fs.appendFile("tasks.json", JSON.stringify(req.body));
}

});

app.listen(3000);

console.log("Express is running on port 3000");

Answer

Try this:

if (!req.body["task"]) {
    res.sendStatus(403);
} else {
    fs.appendFile("tasks.json", JSON.stringify(req.body));
}  

var your_object = {"task":"","important":"true","urgent":"false","quadrant":"2"};

console.log(!JSON.stringify(your_object["task"]));

var your_object = {"task":"hello","important":"true","urgent":"false","quadrant":"2"};

console.log(!JSON.stringify(your_object["task"]));


var your_object = {"task":"","important":"true","urgent":"false","quadrant":"2"};


console.log(!your_object["task"]);


var your_object = {"task":"hello","important":"true","urgent":"false","quadrant":"2"};

console.log(!your_object["task"]);

Comments