1

So I'm using node.js to get info from an API, then sending the response from the API back (mainly to get around cross origin and that fun stuff), so I was wondering how I would check if the response from the API is a certain string? For example, if you put in an invalid username in the api it returns an empty object, which if you do object.toString() it should be {} (I think?), so I was wondering how I would do an if statement checking if the APIs response is {} (something like if(object.toString() = "{}" { do stuff }?)

Here's my code:

app.get('/stats/id64/:steamid64', function(httpRequest, httpResponse) {
    var url = '<api link>&steamid=' +
        httpRequest.params.steamid64;
    request.get(url, function(error, steamHttpResponse, steamHttpBody) {
        httpResponse.setHeader('Content-Type', 'application/json');

        var response = {isValidUser: 'false'};

        if(steamHttpBody.toString() == "{}") {
            httpResponse.send(response);
        } else {
            httpResponse.send(steamHttpBody);
        }
    });
});

Any help is appreciated :)

Connor S
  • 25
  • 7
  • 1
    _“which if you do `object.toString()` it should be `{}` (I think?)”_ — No. Try it in your console. It returns `"[object Object]"`. To get `"{}"`, you need to use `JSON.stringify`. – Sebastian Simon Mar 08 '17 at 00:34
  • 1
    Possible duplicate of [How do I test for an empty JavaScript object?](http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object) – Sebastian Simon Mar 08 '17 at 00:34
  • 1
    Remember `=` and `==` and even `===` are wildly different and you **must** understand the difference. Seeing `=` inside an `if` should immediately stand out as a potential problem. – tadman Mar 08 '17 at 00:35

1 Answers1

3

I think you would be better checking for an actual empty object, than converting it to a string. See here: How do I test for an empty JavaScript object?

But yes, to compare strings in JavaScript, you would typically use ===.

Community
  • 1
  • 1
fubar
  • 16,918
  • 4
  • 37
  • 43