Cross Origin Resource Sharing with PrototypeJS

老子叫甜甜 提交于 2019-12-04 10:09:23

I'm having the same problem. The link @mplungjan shared contains the answer :

You simply have to let the browser know that the x-json header is safe by using the access-control-expose-headers

I'm using this line in Ruby on Rails controller

  headers['Access-Control-Expose-Headers'] = 'x-json'

(This should be quite easy to translate into other programming languages :) )

More details on this page

Please have a look at PREFLIGHT here https://developer.mozilla.org/En/HTTP_access_control

Your issue is that Fx is reacting to the custom headers (X-...) and will trigger preflighting. You will need to have the server return all access-control headers for OPTIONS and POST and have it allow custom headers.

Grzegorz Gierlik

I found solution on other SO question. And it works for me -- details are here.

To sum up -- you need onCreate event in your Ajax.Request which removes non-standard headers:

    onCreate: function(response) { // here comes the fix
        var t = response.transport; 
        t.setRequestHeader = t.setRequestHeader.wrap(function(original, k, v) { 
            if (/^(accept|accept-language|content-language)$/i.test(k)) 
                return original(k, v); 
            if (/^content-type$/i.test(k) && 
                /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(;.+)?$/i.test(v)) 
                return original(k, v); 
            return; 
        }); 
    }

Maybe you can set the origin header yourself in the Ajax Request, like so

new Ajax.Request('some.foreign-host.com/res.php', {
    method: 'post',
    postBody: 'foo=bar',
    requestHeaders: {Origin: 'http://www.my.local-host.com'}
    contentType: 'application/x-www-form-urlencoded', 
    onSuccess: function(e){
        // some custom code
    }
});

Never tried it myself though... What happens with the Prototype version? Is a request being issued and then nothing returns, or is a response being discarded, or what?

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