是否可以在Javascript中进行跨域请求并设置自定义头文件?

时间:2022-08-23 10:19:53

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连接到谷歌数据API很简单,但是它在服务器端始终占用大量的资源解析提要。

3 个解决方案

#1


5  

You can use Google's JavaScript client library to query the Docs API. Although it doesn't come with helpers for Docs specifically, it can still be used with most APIs, including Docs. See this blog post by a Google employee that shows a working example.

您可以使用谷歌的JavaScript客户端库来查询Docs API。虽然它没有专门为文档提供帮助,但它仍然可以用于大多数api,包括文档。请参阅谷歌员工的这篇博文,其中显示了一个工作示例。

If you end up in an infinite loop of authorizations, see this related question from Google groups. 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. 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.

如果您在授权的无限循环中结束,请参见谷歌组的相关问题。基本上,cookie设置得不够快,所以当JavaScript客户端库检查时,它什么也找不到并重新定向到OAuth授权页面。解决方案是要么在检查完成之前添加一个小的延迟,要么使用启动授权的登录按钮,而不是在页面加载时执行授权。

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.

您还需要向位于相同域中的页面添加任何图像。只要在DOM中,它就可以被CSS隐藏。

Using the example in the above blog post, I was able to retrieve my documents list with JavaScript alone. Here's the modified initialize function I used to get rid of the infinite authorization loop:

在上面的博客文章中,我可以单独使用JavaScript检索文档列表。下面是我用来摆脱无限授权循环的修改过的initialize函数:

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);
    }
};  
​

#2


3  

Consider to write some code at the server side which plays for a proxy and let jQuery call it.

考虑在服务器端编写一些代码,这些代码用于代理并让jQuery调用它。

  • If you're using PHP, use curl.
  • 如果使用PHP,请使用curl。
  • If you're using Java, use URLConnection or the more convenienced Apache HttpClient.
  • 如果您正在使用Java,请使用URLConnection或更方便的Apache HttpClient。
  • If you're using C#/.NET, use WebClient.
  • 如果你使用c# /。净,用WebClient。
  • If you're using Ruby, use Net::HTTP.
  • 如果您正在使用Ruby,请使用Net::HTTP。

#3


0  

You can, as long as the external domain allows it by sending an appropriate Access-Control-Allow-Origin header. Then just use the XMLHttpRequest API in browsers that support the standard cross-domain XHR API and XDomainRequest in IE.

只要外部域允许,可以通过发送适当的访问控制允许的源头来实现。然后在浏览器中使用XMLHttpRequest API,这些浏览器支持IE中的标准跨域XHR API和XDomainRequest。

#1


5  

You can use Google's JavaScript client library to query the Docs API. Although it doesn't come with helpers for Docs specifically, it can still be used with most APIs, including Docs. See this blog post by a Google employee that shows a working example.

您可以使用谷歌的JavaScript客户端库来查询Docs API。虽然它没有专门为文档提供帮助,但它仍然可以用于大多数api,包括文档。请参阅谷歌员工的这篇博文,其中显示了一个工作示例。

If you end up in an infinite loop of authorizations, see this related question from Google groups. 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. 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.

如果您在授权的无限循环中结束,请参见谷歌组的相关问题。基本上,cookie设置得不够快,所以当JavaScript客户端库检查时,它什么也找不到并重新定向到OAuth授权页面。解决方案是要么在检查完成之前添加一个小的延迟,要么使用启动授权的登录按钮,而不是在页面加载时执行授权。

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.

您还需要向位于相同域中的页面添加任何图像。只要在DOM中,它就可以被CSS隐藏。

Using the example in the above blog post, I was able to retrieve my documents list with JavaScript alone. Here's the modified initialize function I used to get rid of the infinite authorization loop:

在上面的博客文章中,我可以单独使用JavaScript检索文档列表。下面是我用来摆脱无限授权循环的修改过的initialize函数:

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);
    }
};  
​

#2


3  

Consider to write some code at the server side which plays for a proxy and let jQuery call it.

考虑在服务器端编写一些代码,这些代码用于代理并让jQuery调用它。

  • If you're using PHP, use curl.
  • 如果使用PHP,请使用curl。
  • If you're using Java, use URLConnection or the more convenienced Apache HttpClient.
  • 如果您正在使用Java,请使用URLConnection或更方便的Apache HttpClient。
  • If you're using C#/.NET, use WebClient.
  • 如果你使用c# /。净,用WebClient。
  • If you're using Ruby, use Net::HTTP.
  • 如果您正在使用Ruby,请使用Net::HTTP。

#3


0  

You can, as long as the external domain allows it by sending an appropriate Access-Control-Allow-Origin header. Then just use the XMLHttpRequest API in browsers that support the standard cross-domain XHR API and XDomainRequest in IE.

只要外部域允许,可以通过发送适当的访问控制允许的源头来实现。然后在浏览器中使用XMLHttpRequest API,这些浏览器支持IE中的标准跨域XHR API和XDomainRequest。