Having issue accessing the Discourse APIs from react app

AI-generated summary

The discussion revolves around accessing the Discourse APIs from a React app, with users encountering CORS policy issues.

Initial issues arose with fahadaslam98 when trying to call the Discourse APIs due to the API-key header being blocked by CORS policy. Arkshine suggested the correct header should be User-Api-Key.

Later, fahadaslam98 faced another issue with the api-username header being blocked. Arkshine pointed out the correct headers for the Admin API, while gassim noted that for public JavaScript clients, the Admin API is not allowed and the User API should be used instead.

However, RGJ suggested that if the desired data is publicly available, configuring CORS should be sufficient, and API keys would not be needed. This solution was confirmed by gassim, who linked to a relevant discussion and suggested removing API keys from the headers if CORS is properly configured.

Access to fetch at ‘https://boostfloral.discourse.group/categories.json?’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Request header field API-key is not allowed by Access-Control-Allow-Headers in preflight response.

Getting the above issue when I am trying to call the discourse APIs. I have already added an SSL certificate to my servers. I am adding the CORS options present on my admin panel but still getting this issue.

Has anyone faced something like this and could help me what is the way out of this???

Is it a User API Key? If I’m not wrong, it should be User-Api-Key.

Now I am getting the below response.

Access to fetch at ‘https://boostfloral.discourse.group/latest.json?order=default&ascending=false’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Request header field api-username is not allowed by Access-Control-Allow-Headers in preflight response.

If you’re trying to consume the Admin API (as opposed User API), the header fields required are Api-Key and Api-Username.

I think for public Javascript clients, admin api is not allowed (sadly, this complicates everything, I know!) But you’re going to have to use User API keys specification instead.

For me, I’m still trying to figure out how as well. I just want to pull a .json response that’s publicly available.

If it’s public then configuring CORS should suffice and you should not need to bother with API keys at all.

Yes, thanks! This has been solved for me here: Using JavaScript fetch to get publicly available page from Discourse into an external site (Discourse API) - #2 by pfaffman

@fahadaslam98 as @RGJ said, if the CORS is properly configured then removing the API keys from the headers should work, :+1: