API Returning HTML Instead of JSON At Specific Routes?


(Daniel, CSS Fiddler) #1

In Brief:

  • calling a specific route returns HTML instead of json
  • calling a different route with same code returns json as expected
  • accessing the broken route from the Chrome browser returns json as expected

Long:

I found an error with a URL with .json appended erroring with

FetchError: invalid json response body at //url// 
reason: Unexpected token < in JSON at position 0 

Did a little fiddling and found:

const request2 = 'https://{site-url}/u/{user}/activity.json?api_key={key}';

fetch(request2)
// .then(res => {console.log(res)}) // returns 200
.then(res => {return res.text()}) //.json was swapped for .text here
.then(res => {console.log(res)}) // returns html!

The output of the second console.log(), which we expect to be JSON, is HTML!

The odd thing:

Reusing the same code but a different route:

const request2 = 'https://{site-url}/u/{user}.json?api_key={key}'

returns json as expected. And even stranger, pasting the faulty URL into Chrome returns JSON as expected!

Any suggestions? Is this a discourse bug? Did I set something up wrong? I’m not the site admin but can request to get things fixed if it’s a site setup issue.


(Simon Cossar) #2

If you visit a user’s activity page on Discourse and view the Network tab of your browser’s developer tools, you’ll see that a GET request is made to a URL similar to:

http://forum.example.com/user_actions.json?username=simon

Querying that URL through the API should return JSON.


(Daniel, CSS Fiddler) #3

Thanks.

https://{site-url}/user_actions.json?username={user}&api_key={key}

Does return the content that I need. However, shouldn’t the original path also work? You can see it being called in the network tab when accessing the user activity page and it’s got .json? appended to it.


(Daniel, CSS Fiddler) #4

Continuing to face challenges with this issue in new situations

It seems in some instances the request is processed just fine and in some it fails and returns HTML.

Here I am sending individual requests for a large sequence of posts using the endpoint suggested at

https://docs.discourse.org/#tag/Posts%2Fpaths%2F~1posts~1{id}%2Fget

Suggestions? I still believe there is something wonky going on on the backend that some of these routes would be failing.