Skip to main content
1-Visitor
September 26, 2017
Question

Rest API Service problem from javascript

  • September 26, 2017
  • 3 replies
  • 7542 views

Hi,

I'm trying to create a function call to a service with javascript.

This is my code:

var data = "{\n\t\"input\":{\n\t\t\"space\": \"Hki Pa A 109\",\n\t\t\"type\": \"TEMP\"\n\t}\t\n}";

var xhr = new XMLHttpRequest();

xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {

  if (this.readyState === 4) {

console.log(this.responseText);

  }

});

xhr.open("POST", "https://server-address/Thingworx/Things/PWIMAPI/Services/GetMeasurementPoints");

xhr.setRequestHeader("accept", "application/json");

xhr.setRequestHeader("content-type", "application/json");

xhr.setRequestHeader("appkey", "my-app-key");

xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);

If I run this in postman it returns the correct json-content, but when I run it in a HTML-file on the server I get:

Status Code:

401 Unauthorized

Have anyone had a similar problem before? Any suggestion how to solve this?

3 replies

20-Turquoise
September 26, 2017

How are you authenticating?

3studio1-VisitorAuthor
1-Visitor
September 26, 2017

No extra authentication, just with the appkey.

20-Turquoise
September 26, 2017

Appkey in the url? Is it an 8.0 instance?

If so, https://community.thingworx.com/community/developers/blog/2017/06/08/new-technical-changes-in-thingworx-800#comment-3989

"The Allow Application Key as URL Parameter option can be enabled or disabled on the ThingWorx PlatformSubsystem’s configuration page, accessible at System > Subsystems > PlatformSubsystem > Configuration."

1-Visitor
September 27, 2017

We have an Ionic App working, the only difference between our code and yours:

xhrfetchdata.open("POST", "url" ,true);

//setting up headers

xhrfetchdata.setRequestHeader("Content-Type", "application/json");

xhrfetchdata.setRequestHeader("Accept", "application/json");

xhrfetchdata.setRequestHeader("x-thingworx-session", "true");

xhrfetchdata.setRequestHeader("appKey", token);

3studio1-VisitorAuthor
1-Visitor
September 27, 2017

Is your URL also a https or is it a http?

1-Visitor
September 27, 2017

https of course.

1-Visitor
December 8, 2017

Try, append method=POST in your URL.

POST - to execute/invoke tx services via url.