CORS policy in AJAX requests in JavaScript

You cannot just make requests to other sites via AJAX (cross-origin requests). Such requests are subject to the CORS policy. In short, under this policy, the site to which you send a request must agree to respond to it. To do this, it must return the appropriate HTTP headers.

Let's try it in practice. Let's run two test servers on different ports. The first is at 3001 and the second is at 3002. Let's try to send an AJAX request from the second site to the first one.

Let the first site be ready to accept the following requests:

export default { '/handler/': function({ body }) { console.log(body); return 'success'; } }

Let's send a request from the second site to the first:

button.addEventListener('click', function() { let promise = fetch('http://localhost:3001/handler/', { method: 'post', body: JSON.stringify([1, 2, 3, 4, 5]), headers: { 'Content-Type': 'application/json', }, }); });

As a result, the request will not be executed, and in the browser console we will see an error related to the CORS policy.

In order for the request to be fulfilled, the first server must return special HTTP headers. Let's specify them - and the request from the second site will come to the first:

export default { '/handler/': function({ body }) { resp.setHeader('Access-Control-Allow-Origin', '*'); resp.setHeader('Access-Control-Allow-Headers', '*'); console.log(body); return 'success'; } }
enru