使用$ http服务的AngularJS跨域请求 [英] AngularJS cross-domain requests using $http service

查看:820
本文介绍了使用$ http服务的AngularJS跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Twitch API创建一个简单的Web应用程序来学习AngularJS( https:// github.com/justintv/Twitch-API )但我在执行GET请求时遇到问题,因为它是跨域请求。这就是我所尝试的

I'm trying to learn AngularJS by making a simple web app using the Twitch API (https://github.com/justintv/Twitch-API) but I'm having trouble performing a GET request since it's a cross-domain request. This is what I have tried

angular.module('streamPlaylisterAppServices', []).factory('twitchService', ['$http',
  function($http) {
    return function(usercode){
      console.log("usercode inside service is: " + usercode)
      var authHeader = 'OAuth' + usercode;

      return $http({
        method: 'GET',
        url: ' https://api.twitch.tv/kraken',
        cache: false,
        headers:{
          'Accept': 'application/vnd.twitchtv.v3+json',
          'Authorization': 'OAuth ' + usercode
        }
      })
    };
  }]);

但我得到一个错误:

XMLHttpRequest无法加载 https://api.twitch.tv/kraken 。请求
被重定向到' http://www.twitch.tv/kraken ',对于需要预检的跨源请求,不允许使用

XMLHttpRequest cannot load https://api.twitch.tv/kraken. The request was redirected to 'http://www.twitch.tv/kraken', which is disallowed for cross-origin requests that require preflight.

我知道我需要使用JSONP请求但是如何设置标题?任何人都可以向我展示一个JSONP请求的示例以及如何为它设置标头,就像我在上面的示例中所做的那样?如果我无法在JSONP请求中设置标头,我还要如何设置请求标头?

I know I need to be using a JSONP request but how do I set headers that way? Can anyone show me an example of a JSONP request and how to set headers for it like I did in the example above? If I can't set headers in JSONP requests, how else do I set request headers?

推荐答案

请求:

$http.jsonp('https://api.twitch.tv/kraken/games/top?limit=' + number + '&callback=JSON_CALLBACK')

这将返回给你json,你不会遇到问题XMLHttpRequest

This will return to you json and you wont have problems with XMLHttpRequest

这篇关于使用$ http服务的AngularJS跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆