Polymer core-ajax cross domain issue

前提是你 提交于 2019-12-10 21:15:35

问题


I am trying to do a cross domain call using Polymer and the core-ajax component. I keep getting back No 'Access-Control-Allow-Origin' header is present on the requested resource. My code for the component is below

    <core-ajax id="ajax"
        auto
        url="http://api.meetup.com/2/event_comments/?key=MyKey&event_id=191593992&callback=?"
        on-core-response="{{commentsLoaded}}"
        method='GET'
        contentType='text/javascript'
        handleAs="json">
    </core-ajax>

If I use jQuery and the following snippet, it works

$.getJSON('http://api.meetup.com/2/event_comments/?key=MyKeyc&event_id=191593992&callback=?')

So I guess my question is what voodoo magic is jQuery using that Polymer is not and how do I get around it? I have checked the console and everything looks identical (headers, params etc).


回答1:


As the aptly named Jason P points out in the comments above, you can use polymer-jsonp here.

<polymer-jsonp 
    auto 
    url="http://api.meetup.com/2/event_comments/?key=MyKeyc&event_id=191593992&callback=" 
    on-polymer-response="{{commentsLoaded}}">
</polymer-jsonp>



回答2:


On this note, polymer-jsonp has been deprecated.

The alternative is core-shared-lib which is described here: https://www.polymer-project.org/0.5/docs/elements/core-shared-lib.html

And here is Github resource https://github.com/Polymer/core-shared-lib.

core-shared-lib supports sharing a JSONP-based JavaScript library.




回答3:


I know it been a while, but I just had the same trouble recently, and found Iron-ajax will perform an options request before it does the actual request, so I solved it by add a filter to response the options request. Following is my code in Golang if anyone interested in the details.

origin := c.Request.Header.Get("origin")
method := c.Request.Method

if strings.ToUpper(method) == "OPTIONS" {
    if origin == "" || strings.HasSuffix(origin, "domainname.com") {
        c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With")
        c.Writer.Header().Set("Access-Control-Max-Age", "1728000")
        c.AbortWithStatus(204)
    } else {
        c.AbortWithStatus(400)
    }
}



回答4:


That is deprecated, core-shared-lib substitutes the polymer-jsonp



来源:https://stackoverflow.com/questions/24943956/polymer-core-ajax-cross-domain-issue

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