I have attempted to access the Twitter API within my AngularJS application, but I am encountering the following error.
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.
This is how I made the call.
(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
})
}
}());
You can find the project on plunkr at this link.
If anyone could lend a hand, it would be greatly appreciated.