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 :)

3
  • 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. Commented Mar 8, 2017 at 0:34
  • 1
    Possible duplicate of How do I test for an empty JavaScript object? Commented Mar 8, 2017 at 0: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. Commented Mar 8, 2017 at 0:35

1 Answer 1

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 ===.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.