Skip to main content
1-Visitor
November 25, 2016
Solved

Specifying request headers in ContentLoader functions

  • November 25, 2016
  • 1 reply
  • 4736 views

I've created a service that tries to load and return JSON from a URL that needs the "Accept: application/json" header in order to return JSON.

var params = {
    url: url,
    headers: {Accept:"application/json"}
};
var result = Resources["ContentLoaderFunctions"].LoadJSON(params);

That's basically all it is.  I've tested the URL using Postman and it does indeed return JSON, e.g.:

[{"time":"Wed, 09 Nov 2016 01:22:14 GMT","value":"87"}]

Without the "Accept" header, it returns XML.

However, I cannot get my service to return the JSON object!  Have I specified the header incorrectly?  The LoadJSON snippet says the type of the "headers" parameter is "JSON"; this suggests that what I've done is wrong, since I've used a JavaScript object.  The JSON would be:

"{\"Accept\":\"application/json\"}"

(i.e. a JSON-encoded string) but I've tried this too and got the same result, which is an empty response.  At least that's how it looks via the [Test] button.

What am I doing wrong?!

Best answer by rwiseman

Thanks Carles, that helped me find the problem.  It turns out that if the return base type is JSON, testing the service shows nothing!  It should surely say that valid JSON has been returned but it doesn't!  The only indicator is that "Results:" has a light green background.  So when I returned a string instead of JSON I could see that JSON was actually being returned, and that the format is not what I expected:

{"headers":{"Accept":"application/json"},"array":[{"time":"Wed, 09 Nov 2016 01:22:14 GMT","value":"87"}]}

I "foolishly" expected the JSON returned to be ... well ... the JSON returned from the URL!

1 reply

5-Regular Member
November 29, 2016

Wait what is the actual error that you are seeing? What version of ThingWorx is this?

1-Visitor
November 30, 2016

Did you tried with LoadText first to see if you get an answer?

rwiseman1-VisitorAuthorAnswer
1-Visitor
November 30, 2016

Thanks Carles, that helped me find the problem.  It turns out that if the return base type is JSON, testing the service shows nothing!  It should surely say that valid JSON has been returned but it doesn't!  The only indicator is that "Results:" has a light green background.  So when I returned a string instead of JSON I could see that JSON was actually being returned, and that the format is not what I expected:

{"headers":{"Accept":"application/json"},"array":[{"time":"Wed, 09 Nov 2016 01:22:14 GMT","value":"87"}]}

I "foolishly" expected the JSON returned to be ... well ... the JSON returned from the URL!