Skip to content Skip to sidebar Skip to footer

How To Serve Pre-flight Request From Web Service

I have a web service which works over GET. To access this web service, some custom headers need to be passed. When I try to access the web service from javascript code with GET me

Solution 1:

Two things to check for (with no idea what your server-side language / technique is):

  1. Are you including OPTIONS as a valid method in your Access-Control-Allow-Methods? Example:

    Access-Control-Allow-Methods: GET, OPTIONS
  2. Are the custom headers that your request sending being returned to the browser as allowed? Example:

    Access-Control-Allow-Headers: X-PINGOTHER 

The remote server has to return both of these (and most definitely the second one) before any secure, standards-compliant browser (ie not older versions of IE), will allow the non-origin response to come through.

So, if you wanted to implement this at the HTTP server level and keep your web-service portable, you might try the following:

We'll assume your web-service URL is http://example.org/service and that the path to service is /srv/www/service

If you are running Apache 2.0, the syntax to append headers is add, on 2.2, use set.

So, you would modify /srv/www/service/.htaccess with:

 Header set Access-Control-Allow-Methods "GET, OPTIONS"
 Header set Access-Control-Allow-Headers "X-MY_CUSTOM_HEADER1,X-MY_CUSTOM_HEADER2"
 Header set Access-Control-Allow-Origin "*"

Of course, the mod_headers Apache module needs to be on for the above to work. Also, setting the allow-origin to the wild card is risky, and it will actually cause the request to fail if you are sending the Access-Control-Allow-Credentials: true header (can't use wild cards in that case). Also, with the SetEnvIf mod for Apache, you could fine tune the htaccess file to only return the headers when appropriate, rather than for all requests to that directory.

Post a Comment for "How To Serve Pre-flight Request From Web Service"