Skip to main content
1-Visitor
Sep 26, 2017 11:13 AM UTC
Question

Rest API Service problem from javascript

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?

11 replies

20-Turquoise
Sep 26, 2017 12:42 PM UTC

How are you authenticating?

Translate
3studio1-VisitorAuthor
1-Visitor
Sep 26, 2017 12:44 PM UTC

No extra authentication, just with the appkey.

Translate
20-Turquoise
Sep 26, 2017 12:53 PM UTC

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

Translate
1-Visitor
Sep 27, 2017 7:20 AM UTC

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

Translate
3studio1-VisitorAuthor
1-Visitor
Sep 27, 2017 8:19 AM UTC

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

Translate
1-Visitor
Sep 27, 2017 8:21 AM UTC

https of course.

Translate
1-Visitor
Dec 8, 2017 8:08 AM UTC

Try, append method=POST in your URL.

POST - to execute/invoke tx services via url.

Translate