2015-12-10 41 views
0

我想在我的angularjs應用程序中訪問twitter api,但我得到下面的錯誤。在Angular應用程序中使用Twitter api

OPTIONS https://api.twitter.com/oauth2/token (anonymous function) @ angular.js:10765sendReq @ angular.js:10558serverRequest @ angular.js:10268processQueue @ angular.js:14792(anonymous function) @ angular.js:14808Scope.$eval @ angular.js:16052Scope.$digest @ angular.js:15870Scope.$apply @ angular.js:16160bootstrapApply @ angular.js:1679invoke @ angular.js:4523doBootstrap @ angular.js:1677bootstrap @ angular.js:1697angularInit @ angular.js:1591(anonymous function) @ angular.js:29013trigger @ angular.js:3057defaultHandlerWrapper @ angular.js:3346eventHandler @ angular.js:3334 
index.html:1 XMLHttpRequest cannot load https://api.twitter.com/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400. 

我已經完成了以下方式的調用。

(function(){ 
    angular.module('app') 
     .controller('MainController', MainController); 

    function MainController($resource, $http){ 
     var vm = this; 


     //serviceModule.factory('twitter', function ($resource, $http) { 
      var consumerKey = encodeURIComponent('9xF1UTxxoDcTOwikPUid5WZL7'); 
      var consumerSecret = encodeURIComponent('oJRGEF00LtnxZNVtAo6Q7yEuEeqoZrWwMsirN9lwTc5i7ggluP'); 
      var credentials = consumerKey + ':' + consumerSecret; 
      // Twitters OAuth service endpoint 
      var twitterOauthEndpoint = $http.post(
       'https://api.twitter.com/oauth2/token' 
       , "grant_type=client_credentials" 
       , {headers: {'Authorization': 'Basic ' + credentials, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}} 
      ) 
      twitterOauthEndpoint.success(function (response) { 
       // a successful response will return 
       // the "bearer" token which is registered 
       // to the $httpProvider 
       //serviceModule.$httpProvider.defaults.headers.common['Authorization'] = "Bearer " + response.access_token 
       console.log(response); 
      }).error(function (response) { 
        // error handling to some meaningful extent 
       }) 
       } 

    }()); 

鏈接到我的項目上plunkr是http://plnkr.co/edit/BcA0w5OpHjchJzjgipUO?p=preview

可能有人請幫忙。

回答

0

您應該在兩者之間使用您的服務器,因爲您不能讓瀏覽器調用未啓用的資源。你也必須揭示你的API密鑰。

更多信息:CORS

+0

謝謝,但我不明白 – vishesh

+0

@vishesh您應該運行的,而不是試圖從瀏覽器直接連接到API,您的前端代碼連接到服務器。 –

相關問題