My Flutter web app needs to call an API when the user submits a contact form. The API is that of a discord bot that proceeds to post the message in a specific channel on my Discord server. This setup works fine for two other apps that are using the same dependencies and the same production environment (Firebase hosting), but on this specific app it throws the following error:
Access to XMLHttpRequest at 'https://discordapp.com/api/channels/689799838509957177/messages' from origin 'https://autonet.tk' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If I add the header 'Access-Control-Allow-Origin': '*'
to the request, I just get a XMLHttpRequest error
My code:
import 'package:http/http.dart' as http;
var resp = await http.post(
"https://discordapp.com/api/channels/689799838509957177/messages",
headers: {
'Authorization': "Bot " + botToken,
},
body: {
"content": "NEW MESSAGE: " + body
});
Making it harder to triangulate the root cause is the fact that this runs fine on my local machine. It's only once I deploy the app to Firebase hosting that I get that CORS error. Another thing worth noting is that on the Discord side, there is no configuration that I had to make in order to accept the incoming request for the other two web apps that work fine using the same code. (There is no list of allowed hosts).
'Access-Control-Allow-Origin' it's a header that must be in the response, not in the request. For more information, I suggest you this read:
https://stackoverflow.com/a/20035319/14106548
EDIT: After a small research I think you are calling the wrong endpoint. This is why the response doesn't have the proper header attached. The endpoint is:
For more info look at: https://discord.com/developers/docs/reference