how to serve pre-flight request from web service

北战南征 提交于 2019-12-11 11:42:08

问题


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 method, the request method is getting changed to OPTIONS. (the domain is different)

I read some articles to find out that a request with Custom headers will be pre-flighted and in that case before the actual method call, a request with OPTIONS method will be made to the server.

But my problem is after the OPTIONS call, the real method (i.e GET) is not being invoked.

The OPTIONS call is returning the status as 401.

I doubt this is because my web-service supports GET only. How can I solve the problem? Kindly help. (My code is working fine with IE but not with other browser e.g. Chrome)


回答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.



来源:https://stackoverflow.com/questions/10314255/how-to-serve-pre-flight-request-from-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!