When setting http authorization headers the AngularJS app crashes - angularjs

I want to make a request to the twitter api and get the current logged in userfeed.
I tryed the twitter api with "apigee" and everything works fine. Even when copying the Authorization header from "apigee" into "postman" I get back data.
Well but when I try to make the http-request in my angular-app, the whole app stops working.
In the browser there ist just the output "{{message}}" and the console prints two error messages:
Uncaught SyntaxError: Unexpected identifier :3000/javascripts/app.js:211
Uncaught Error: No module: app angular.min.js:17
The code in my app looks like this
app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url,
{headers: {
'Authorization':
Oauth oauth_consumer_key = "xxxx",
oauth_signature_method="HMAC-SHA1"
oauth_timestamp="1401883718",
oauth_nonce="840988792",
oauth_version="1.0",
oauth_token="xxxx",
oauth_signature="xxx"
}})
.then(function (data) {
$scope.data = data.data;
console.log(data);
});
Can anyone help me or tell me what I'm doing wrong.
Kevin

try this way:
app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url, {
headers: {
'Authorization':
'Oauth oauth_consumer_key = "xxxx",' +
'oauth_signature_method="HMAC-SHA1",' +
'oauth_timestamp="1401883718",' +
'oauth_nonce="840988792",' +
'oauth_version="1.0",' +
'oauth_token="xxxx",' +
'oauth_signature="xxx"'
}
}).then(function (data) {
$scope.data = data.data;
console.log(data);
});

Related

XMLHttpRequest cannot load .... Response for preflight has invalid HTTP status code 401

Below is my service call where I am trying to do a basic auth. I have checked multiple blogs could not find the solution for this.
Can anybody help me to solve this issue as I am getting below error:
XMLHttpRequest cannot load
Response for preflight has invalid HTTP status code 401
I could not find the basic auth in the network tab in developer options also.
function() {
"use strict";
var APIservice = function($http, $base64) {
var getDetails = function(postData) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";
$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Content-Type, Authorization, Content-Length, X-Requested-With";
$http.defaults.headers.common['Content-Type'] = undefined;
console.log($http.defaults.headers.common.Authorization);
//console.log($http.defaults.headers.common.Authorization);
return $http.get('http://52.74.68.202:8080/rest/v1/step/all')
.then(function(response, headers, config) {
console.log(response);
return response;
});
};
return {
getDetails: getDetails
}
}
var module = angular.module('expframework');
module.factory("APIservice", APIservice);
module.run(['$http', '$base64', function($http, $base64) {
var authdata = $base64.encode('test:test');
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}]);
module.config(['$httpProvider', '$base64', function($httpProvider, $base64) {
var authdata = $base64.encode('test:test');
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}])
}();
It is working in Safari and emulators but not working in Chrome and Firefox
Please help me to fix this. Thanks in advance.
Since your server threw a 401, I guess it tried to authenticate the preflight request. From https://stackoverflow.com/a/15734032/1225328:
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded.
[...]
Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

Angularjs - 500 (Internal Server Error) on $http Post

I am new to Ionic and angular. I am building a sample with ionic framework using angular.js. I want to call WebApi through $http post method. I checked this(ionic-proxy-example) solution and I am trying to implement the same using my api. When I call the api provided in above example in my sample project, I get the records but its not working with my api. It throws 500 internal error.
Here is my app.js
angular.module('myApp', ['myApp.controllers', 'myApp.services'])
.constant('ApiEndpoint', {url: 'http://localhost:8100/api'})
Services.js
angular.module('myApp.services', [])
.factory('Api', function($http, $q, ApiEndpoint) {
console.log('ApiEndpoint', ApiEndpoint)
var getApiData = function() {
var q = $q.defer();
var data = {
Gameweek_ID: '179',
Vender_ID: '1',
Language:'en'
};
var config = {
headers : {
"Content-Type": "application/json; charset = utf-8;"
}
};
$http.post(ApiEndpoint.url, data, config)
.success(function (data, status, headers, config) {
// $scope.PostDataResponse = data;
alert('success');
console.debug("response :" + data);
q.resolve(data);
})
.error(function (data, status, header, config) {
// $scope.ResponseDetails = "Data: " + data +
alert('error');
console.debug("error :" + data);
q.reject(data);
});
return q.promise;
}
return {getApiData: getApiData};
})
controllers.js
angular.module('myApp.controllers', [])
.controller('Hello', function($scope, Api) {
$scope.employees = null;
Api.getApiData()
.then(function(result)
{console.log("result is here");
jsonresponse = result.data;
$scope.employees = jsonresponse;}
)
});
And Ionic.Project File
{
"name": "Multilingual",
"app_id": "4b076e44",
"proxies": [
{
"path": "/api",
"proxyUrl": ""
}
]}
I am trying to understand the problem and checked multiple methods to call the api. Surprisingly, it works with ajax post call without any CORS errors. As I am using Angular, I am trying to get this done through $http post. I feel it is some minor issue but I am not able to figure out. Will be grateful for solutions. Thank you.
You've set the content type to json so the sever is expecting a json string but isn't receiving a properly formatted json string as you're sending through an object and hence the error.
Where you have $http.post(ApiEndpoint.url, data, config) change it to $http.post(ApiEndpoint.url, JSON.stringify(data), config).
If that doesn't work, change your content type to application/x-www-form-urlencoded and update this line $http.post(ApiEndpoint.url, data, config) to $http.post(ApiEndpoint.url, $httpParamSerializer(data), config) , don't forget to inject the $httpParamSerializer function.
The problem is that you are sending a POST with $http.post request instead of a GET request with $http.get
Try as below-
$http({
url: ApiEndpoint.url,
method: "POST",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).Success(..rest code goes here..)
In WebAPI, when we pass more than one object in POST method, we get 500 internal error and hence we use ViewModel in such scenarios(talking about asp.net MVC).

angular laravel nginx 400 Bad Request

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help
Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

How to Upload file to S3 using Angular/Node ng-file-upload

Unable to get file upload to S3 working. That being said, I know the problem is on my end.
At the moment I can upload a file to S3 using: https://s3.amazonaws.com/doc/s3-example-code/post/post_sample.html
Now if I copy and paste the form to my app, and just Post the form, it works.
Next step I'm doing is to move the hardcoded values into the Angular controller to attempt uploading the file through there before implementing server side creation of policy and signature, although it doesn't seem to work.
Error I'm getting is the Authorization: Bearer issue.
After reading it, I've tried setting Authorization to undefined, and that still isn't working and I'm at a loss.
Any help would be appreciated.
Code below:
var mypolicy = "HardcodedPolicy;
var mysignature = "HardcodedSignature";
var s3url = "https://myBucket.s3.amazonaws.com/";
Upload.upload({
url: s3url,
method: 'POST',
headers: {
'Authorization': undefined
},
data: {
key: 'testfile.txt',
acl: 'public-read',
"Content-Type": 'text/plain',
AWSAccessKeyId: 'XXX',
policy: mypolicy,
signature: mysignature,
file: uploadfile
}
}).error(function(err) {
console.log("err: ", err);
})
I have spent ages trying to find a solution to this and finally got it to work. I hope this solution helps others. In my case the problem was caused by our app using jwt tokens to authenticate users whenever they make calls to our api. The code which added the token was in an angular factory like this:
App.factory('authInterceptor', ['$rootScope', '$q', '$cookieStore', '$location','$window',
function ($rootScope, $q, $cookieStore, $location, $window) {
return {
// Add authorization token to headers
request: function (config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
}
}]);
The solution we used was to amend the conditon statement so the authorization header was only added if required. We changed the 'if' statement to
if ($cookieStore.get('token') && config.url != "https://yourbucket.s3.amazonaws.com/")
Hope this helps someone else.

Authorization header in AngularJS not working

I am using the Django REST token authentication for my API.
I posted my credentials to obtain token endpoint. However when I try to set the header in a correct way it keeps responding with a http 401 error. I tried it using curl -X GET http://127.0.0.1:8000/events/ -H 'Authorization: Token 4d92d36768ca5d555b59cf68899eceab39c23704 ' and that does work! This is my code:
app.controller('HomeController', ['$scope','$http', function($scope,$http) {
$scope.username = '';
$scope.password = '';
$scope.submitLogin = function () {
var credentials = {
username : $scope.username,
password : $scope.password,
};
var req = $http.post('http://127.0.0.1:8000/api-token-auth/', credentials);
req.success(function(data, status, headers, config) {
$scope.token = data.token;
var str1 = 'Token ';
$scope.tokenheader = str1.concat($scope.token);
$http.defaults.headers.common.Authorization = $scope.tokenheader;
});
req.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
};
$scope.getEvents = function () {
var req = {
method: 'GET',
url: 'http://127.0.0.1:8000/events/',
}
$http(req).then(
function() {
console.log('succes')
},
function(){
console.log('fail')
});
};
}]);
And the error message in chrome dev tools:
XMLHttpRequest cannot load http://127.0.0.1:8000/events/.
Response for preflight has invalid HTTP status code 401
How do I get rid of this 401 error?
Edit: I just found out the fault lies in the fact that I did not have CORS installed on my API. I was using a CORS plugin in chrome that worked for the authentication part of my api but not for my events url!
Did you check that the token is actually added to your request?
You can do this for example using the Chrome developers tools.
Personally I prefer to use the $httpprovider.interceptor as described in:
angularjs $httpProvider interceptor documentation
This ensures that the tokens are always present on any call.
If you are accessing more than one API, you should consider adding something like:
$httpProvider.interceptors.push(['$q', '$location', '$log', 'loginService', 'restHelperService',
function ($q, $location, $log, loginService, restHelperService) {
return {
request: function (config) {
// check if the request comes with an url
if (config.url) {
// check that the call is to the REST api, if yes add token
if (restHelperService.isRestCall(config.url)) {
// add auth header or revert to login
if (loginService.userIsLoggedIn()) {
config.headers = config.headers || {};
config.headers.Authorization = 'Token ' + loginService.getToken().token;
} else {
$location.path('/login');
}
}
}
return config;
},
responseError: function (response) {
if (response.status === 401 || response.status === 403) {
// clear auth token if the REST call failed with the current token
if (response.config && response.config.url && restHelperService.isRestCall(response.config.url)) {
$log.debug(" restCall failed due to bad credentials, resetting credentials");
loginService.resetCredentials();
$location.path('/login');
}
}
return $q.reject(response);
}
};
}]);
}])
This avoid issues that will arise when you start adding the token to API calls that don't expect them. Also the code ensures that a user will be automatically redirected to the login page if the credentials are not valid.
The example, I'm using two additional services. A loginService that manages the tokens and a restHelperService that manages the urls of the REST framework.
I would recommend doing the same as else it will be hard to access the credentials from outside your controller.
You need to add Token to the headers:
get($http, "/some_url", {headers: {"Authorization": "Token " + $your_token}}
....
....
);
Response code 401 means Unauthorized. If you are using Token based authentication then in case of fail it would be 403, Forbidden.
So my guess would be that it's username/password who is messing with it. In your curl example you are not using them.

Resources