CORS - Cross-Origin Resource Sharing - Vanilla Success
<main> <article class="userContent"> <p>Cross-origin resource sharing allows pages on other domains to access the API. In order to take advantage of CORS support you’ll have to specifically whitelist each domain you want to grant access, to ensure that no bad actors are calling your API from sites you don’t control.</p><h2 data-id="whitelisting-domains-for-cors">Whitelisting Domains for CORS</h2><p>To whitelist a domain and grant it access to the API, take the following steps.</p><ol><li>Go into <strong>Dashboard › Settings › Security</strong>.</li><li>Add the domain you want to whitelist to the <strong>Trusted Domains</strong> list. Just enter the domain without the “<a href="https://”" rel="nofollow noreferrer ugc">https://”</a> part.</li></ol><h2 data-id="making-a-cors-request">Making a CORS Request</h2><p>Most javascript AJAX clients support CORS transparently so you won't have to do anything special once the site has whitelisted your domain. If you are unsure if your client is making the request properly then open up your network inspector and make sure the request has the <strong>Origin</strong> header and it includes your domain. That is the domain that must be whitelisted in Vanilla.</p><h2 data-id="avoiding-pre-flighted-requests">Avoiding Pre-flighted Requests</h2><p>CORS has the concept of “pre-flighted requests” which involves the browser making an initial request to see if it has authorization and then the actual request if everything checks out. Pre-flighted requests are suboptimal because they essentially double up the requests you have to make.</p><p>Fortunately, the API has a workaround to avoid most pre-flighted requests. Here are the steps you need to take.</p><ol><li>Pass the access token in the <strong>access_token</strong> querystring rather than the authorization header. If you do this, leave out the “Bearer” part of the access token.</li><li>GET requests that contain the access token in the querystring should avoid pre-flight requests.</li><li>When you make a POST request you can’t set the content type to application/json or else it will trigger a pre-flight request. If you want to post JSON you can set your content type to text/plain and the API will assume it’s application/json.</li><li>If you are still noticing pre-flight requests then you are probably adding some sort of header to your request. Look at <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests" rel="nofollow noreferrer ugc">MDN’s help on simple requests</a> to see what extraneous header may be triggering the pre-flight.</li></ol><p>These workarounds are only necessary if you are making requests within a browser. If you are making requests elsewhere then you should set the access token in the header and use a content type of application/json.</p> </article> </main>