简体   繁体   English

是否可以在Javascript中设置跨域请求并设置自定义标头?

[英]Is it Possible to Make Cross-Domain Requests in Javascript AND Set Custom Headers?

Since you can't apply custom headers on JSONP calls , how do I make cross domain requests AND apply custom headers using jQuery? 由于您无法在JSONP调用上应用自定义标头 ,如何使用jQuery创建跨域请求并应用自定义标头?

I'm basically trying to access google docs with jQuery and need to pass an authentication token: 我基本上试图使用jQuery访问谷歌文档,并需要传递身份验证令牌:

var token = "my-auth-token";
$.ajax({
  url: "http://docs.google.com/feeds/documents/private/full?max-results=1&alt=json",
  dataType: 'json',
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
  },
  success: function(data, textStatus, XMLHttpRequest) {
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
  }
});

Note: The goal of this is to completely bypass the application layer. 注意:这样做的目的是完全绕过应用程序层。 It's simple to use ruby to connect to the Google Data API, but it takes up a lot of resources parsing feeds all the time server-side. 使用ruby连接到Google Data API很简单,但是它会占用很多资源,一直在服务器端解析Feed。

You can use Google's JavaScript client library to query the Docs API. 您可以使用Google的JavaScript客户端库来查询Docs API。 Although it doesn't come with helpers for Docs specifically, it can still be used with most APIs, including Docs. 虽然它没有专门为Docs提供帮助程序,但它仍然可以与大多数API一起使用,包括Docs。 See this blog post by a Google employee that shows a working example. 请参阅Google员工的博文 ,其中显示了一个有效的示例。

If you end up in an infinite loop of authorizations, see this related question from Google groups. 如果您最终获得无限授权,请参阅Google网上论坛中的相关问题 Basically, the cookies aren't getting set fast enough, so when the JavaScript client library checks, it finds nothing and redirects to the OAuth authorization page. 基本上,cookie的设置速度不够快,因此当JavaScript客户端库检查时,它什么也找不到,并重定向到OAuth授权页面。 A solution is to either add a small delay before the check is done, or use a login button that initiates the authorization instead of doing it on page load. 解决方案是在检查完成之前添加一个小延迟,或者使用启动授权的登录按钮而不是在页面加载时执行。

You would also need to add any image to your page that resides on the same domain. 您还需要将任何图像添加到位于同一域中的页面。 It can be hidden with CSS, as long as in the DOM. 它可以用CSS隐藏,只要在DOM中。

Using the example in the above blog post, I was able to retrieve my documents list with JavaScript alone. 使用上面博客文章中的示例,我能够仅使用JavaScript检索我的文档列表。 Here's the modified initialize function I used to get rid of the infinite authorization loop: 这是我用来摆脱无限授权循环的修改初始化函数:

function initialize() {
    var scope = 'http://docs.google.com/feeds/';

    if (google.accounts.user.checkLogin(scope)) {
        var service = new google.gdata.client.GoogleService('writely', 'DocList-App-v1.0');   
        service.getFeed(scope + 'documents/private/full/', handleFeed, handleError);  
    } else {
        var loginButton = $("<button>Click here to login</button>");
        loginButton.click(function() {
            var token = google.accounts.user.login(scope); // can ignore returned token  
        });
        $("body").append(loginButton);
    }
};  
​

Consider to write some code at the server side which plays for a proxy and let jQuery call it. 考虑在服务器端编写一些代码,用于代理并让jQuery调用它。

You can, as long as the external domain allows it by sending an appropriate Access-Control-Allow-Origin header. 只要外部域允许通过发送适当的Access-Control-Allow-Origin标头,您就可以。 Then just use the XMLHttpRequest API in browsers that support the standard cross-domain XHR API and XDomainRequest in IE. 然后在支持IE中的标准跨域XHR API和XDomainRequest浏览器中使用XMLHttpRequest API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM