Make cross-domain AJAX request

1

By default you can't do cross-domain AJAX requests. This can be solved in the following way:

Assume you want to do AJAX request from samblog.com to coolapi.com. To do that coolapi.com website should add the following HTTP headers to the response:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range
Access-Control-Expose-Headers: Content-Length, Content-Range

As you see, header names are quite self-documented. You can specify what headers should be accepted as well as which headers should be sent back. In the example above parameter Access-Control-Allow-Origin allows AJAX requests from any origin. That can be restricted like that:

Access-Control-Allow-Origin: https://samblog.com

Now only AJAX requests from https://samblog.com are allowed.

Share this page:

See also how to:

How to display beautiful math formulas on your website with MathJax JavaScript library
How to use WebSockets in web browser with JavaScript
How to use web browser local storage in JavaScript and what you should now about it
How to pass messages between different HTML iframes and the main window.
How to install NGINX web-server on Linux and confiure its basic settings