0

I am getting my head around express and have this get method:

app.get('/myendpoint', function(req, res) {
    var js= JSON.parse ({code: 'success', message:'Valid'});
    res.status(200).json(js);
});

When this endpoint is hit I get an error:

_http_server.js:192
    throw new RangeError(`Invalid status code: ${statusCode}`);

When I comment out the JSON.parse statement and replace the js for some valid json it has no issues? How can I fix this?

bier hier
  • 20,970
  • 42
  • 97
  • 166
  • 1
    [JSON](http://json.org) != "a JavaScript object" and is *not* created by using JavaScript Object Literal Syntax! Try passing in *actual* JSON, which is *text*. (If starting with a JavaScript object and converting it *to* JSON, such as when sending a reply, there is no need for `JSON.parse` at all.) – user2864740 Jul 01 '16 at 02:42

2 Answers2

1

No need to JSON.parse() in this situation. The function call done incorrectly, since the function expects a string, not an object.

This should work just fine:

app.get('/myendpoint', function(req, res) {
    res.status(200).json({code: 'success', message:'Valid'});
});

More info in the Express docs.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

I figured it out:

res.status(200).send(js);

Works.

bier hier
  • 20,970
  • 42
  • 97
  • 166