Help:CORS Setup

From OpenLiteSpeed
Jump to: navigation, search

Enabling Cross-Origin Resource Sharing

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access. CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests.

How to Enable

Navigate to Web Admin > Configurations > Your Virtual Hosts > Context:

  1. Click the Add button
  2. Choose Static type
  3. Set URI to / (You can change this if you want to)
  4. Set Location to $SERVER_ROOT/Example/html/ (You can change this if you want to)
  5. Set Accessible to Yes
  6. Set Extra Headers to Access-Control-Allow-Origin
  7. Click the Save button
  8. Do a graceful restart
    Cors-2-2.png

    Cors-1-1.png

How to Verify

Before verification

Check that our response header includes Access-Control-Allow-Origin *.
Cors-6.png

Start verification

Testing CORS is not easy. Here we are going to use the Test-cors online tool to verify it with simple steps.
The tool looks like this. We need to enter the HTTP Method and Target Remote URL
Cors-3.png

  • Send Request with the default supported method, e.g. GET:
    Cors-4.png
  • Send Request with an unsupported method, e.g. DELETE:
    Cors-5.png
  • You can also copy the code from the testing tool to test on your own:
var createCORSRequest = function(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // Most browsers.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // IE8 & IE9
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
};

var url = 'http://Your_Domain/xxx';
var method = 'DELETE';
var xhr = createCORSRequest(method, url); 

xhr.onload = function() {
  // Success code goes here.
};

xhr.onerror = function() {
  // Error code goes here.
};

xhr.send();

How to support more methods

By default, CORS supports the following methods: PUSH, GET and HEAD. What if you want to support OPTIONS and DELETE, as well?

You can simply append to Extra Headers: Access-Control-Allow-Methods GET, POST, OPTIONS, DELETE.
Cors-3-3.png

Try verification again, sending the DELETE HTTP method. You should see a 200 response.
Cors-8.png

More Information