在Angular应用程序中使用Twitter api

时间:2015-12-10 17:41:07

标签: javascript angularjs twitter twitter-oauth

我正在尝试在我的angularjs应用程序中访问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

有人可以帮忙。

1 个答案:

答案 0 :(得分:0)

您应该在两者之间使用您的服务器,因为您无法让浏览器调用未启用的资源。此外,您还必须透露您的API密钥。

更多信息:CORS