I recently create a landing page where I manually have added a form from which users can subscribe to a newsletter.
The newsletter access uses the SendGrid APIs, and these are the parameters I have set up for the POST request:
var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.open("PUT", "https://api.sendgrid.com/v3/marketing/contacts"); xhr.setRequestHeader("authorization", "Bearer <API_KEY>"); xhr.setRequestHeader("content-type", "application/json"); xhr.setRequestHeader("Access-Control-Allow-Credentials", true); xhr.setRequestHeader("Access-Control-Allow-Origin", true);
however, when I try to send the below code I have the following error:
Access to XMLHttpRequest at 'https://api.sendgrid.com/v3/marketing/contacts' from origin 'https://ilbrucomela.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Also, the following line on the console is this:
PUT https://api.sendgrid.com/v3/marketing/contacts net::ERR_FAILED
which has also a pointer to this line on the file https://cdn.shopify.com/s/assets/shop_events_listener.js
Note: On the SendGrid side, I also tested the API with Full Access
Any help would be deeply appreciated, thanks!
A solution would be to set up your own backend that interacts between the user and the SendGrid API. That way you can make sure what gets in is validated. Keep in mind that the response needs to include cross-origin resource headers, not the request. Here is a snippet I use with NGINX:
add_header 'Access-Control-Allow-Origin' "$http_origin" always; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type';
I add these headers depending on the origin with the built in variable $http_origin. I'm sure the same thing can be done with other web servers, just make sure to include those headers in the response and you won't run into CORS issues. If you wish to debug your app locally without these headers in the response, you could run Google Chrome with the following flag "--disable-web-security".