Daniel Wee
Daniel Wee

Reputation: 1

Node.js Express delete req.body not working

router.delete('/board', function (req, res, next) {
var body = req.body;

if (!isEmpty(body)) {
    var index = findIndexInList(body);
    list.splice(index,1);
    res.sendStatus(200);
    return;
}
list=[];
res.sendStatus(200);
});



function findIndexInList(key) {

  for (var index in list) {
    var value = list[index];
    //value = { '{data:"2"}': '' } TypeOf = Object
    //key = { '{data:"2"}': '' } TypeOf = Object
    console.log(value === key); // why false? I think same so TRUE..
    if( value === key ) {
        return list.indexOf(value);
    }
}
return undefined;
}

Hello. Let me ask a few questions about req.body.
when I send data from client such as chrome console

(
$.ajax({
type: 'delete',
data : '{data:"2"}
});)

in server-side, LIST array have data.
so I sent same data to server-side.

for example

list = [{ '{data:"1"}': '' },{ '{data:"2"}': '' } ];
//value = { '{data:"2"}': '' } Type = Object
//key = { '{data:"2"}': '' } Type = Object
console.log(value === key); // FALSE

why false? I think same object and data so TRUE..

Upvotes: 0

Views: 642

Answers (2)

user4466350
user4466350

Reputation:

When javascript tests for object equalities, using double or triple eq, it will always check for internal references. ref here

Running this

var g = {some: 'thing'}
console.log({} == {});
console.log({a:1} == {a:1});
console.log({a:1} == {a:2});
console.log({} === {});
console.log(g === g);
console.log(g == g);

gives us

false
false
false
false
true
true

If you need to test equality of Object's contents, you should use something like this module https://github.com/substack/node-deep-equal

As you can see here it is able to tell you if two differents objet instances have the same content or not.

you can also use the stringified tip as mentionned.

Upvotes: 0

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22895

You are comparing Objects in javascript which is not possible this way. There is no good way to compare objects. However if your object is simple, with no methods then you can compare after converting it to json string

{} !== {}
key = { '{data:"2"}': '' }
value =  { '{data:"2"}': '' }
JSON.stringify(key)  === JSON.stringify(value)

Upvotes: 1

Related Questions