Ich baue gerade eine Headless-WP-Seite für ein Magazin, dessen Community auf Discourse läuft. Die Kommentare sollen in die Artikelseiten integriert werden. Ich habe die API-Dokumentation gefunden und war sehr erfreut, da das Iframe-Embed nicht wirklich das war, was ich suchte, da die Website über einen Dunkel- und Hellmodus verfügt. Daher muss die Kommentartemplate die CSS-Variablen vom Root-Element erben.
Allerdings stoße ich beim direkten Zugriff auf die API (mittels fetch auf https://discourseurl.com/t/{id}.json) ständig auf das Ratenlimit. Daher habe ich überlegt, einen API-Schlüssel hinzuzufügen und mich damit zu authentifizieren.
Ich verwende folgenden Code:
fetch(this.apiUrl, {
headers: {
'User-Api-Key': '{Benutzer-API-Schlüssel aus dem Discourse-Admin}',
},
})
Ich erhalte jedoch diese Fehlermeldung, egal welchen Schlüssel ich verwende (auch mit einem Admin-Schlüssel):
error_type: "invalid_access"
errors: Array [ "Du hast keine Berechtigung, die angeforderte Ressource anzuzeigen." ]
(Grobe Übersetzung: „Sie haben keinen Zugriff auf die angeforderte Ressource".)
Verpasse ich etwas bezüglich der Funktionsweise von API-Schlüsseln? Was wäre der empfohlene Ansatz, um diese API-Endpunkte abzurufen, ohne das Ratenlimit zu erreichen?
Have a look at the Authentication section that’s near the top of https://docs.discourse.org/. It gives an example of how to set your API credentials in the request header. You need to use Api-Key and Api-Username in the header.
Thanks! Can’t imagine how I missed the auth part there, been looking through the docs over and over again
Anyway, I seem to be making some kind of progress, but I run into this issue now in the browser console: (Reason: missing token ‘api-key’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
I’m not sure what might be causing it, can’t find anything in the forum about it either. Am I missing something? Weird thing is that I am specifying the header as ‘Api-Key’ in my code. Any ideas?
Sounds like you are building a JavaScript app and making the API requests from the browser?
The recommended approach would be to make the API calls to Discourse server side, and have your JavaScript app talk to your server just how it talks to WordPress. This way you avoid any CORS issues.
Ah, awesome! This made me look through the WP Discourse code and realize I’m just an option away from WP exposing the API endpoint I need (exposing the Discourse comments via an API). I’ll just have to tweak it a little bit. That’s excellent, thanks a bunch
Just curious, why isn’t it recommended to work directly against the Discourse API from the client side? I have some ideas on expanding on the project later on if there will be any budget (with a login functionality, for example), and I would like it to talk with the Discourse API. Would I have to route everything through Wordpress?