AngularJS How to include header in Http request - angularjs

I am new to angularjs. I am trying to make an API request that requires authorization. I have included it in the header of the request, but it is still not working. I am sure my access token is working. Any advice?
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({
method: $scope.method,
url: $scope.url,
cache: $templateCache,
headers: {
Authorization: "access token"
}
}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};

You could use following
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
It will add the above header to every POST call you make from your app. For adding a header common to all method, try following.
$http.defaults.headers.common['Authorization'] = "Bearer " + user.oauthInfo.access_token;

Do you see the header in your browser's network request log for the Request?
If so, is it in the expected format? Typically the "Authorization" header will have something before it, like "Basic " (as DevPat mentions in a comment above) or "Bearer ". What belongs here is dependent on the backend system receiving the request.
Examples of expected header:
Authorization: Bearer access_token
Authorization: Basic access_token

Related

AngularJS : Implementing token in $http

I am very new to angularJS.
My Backend is DRF and I have successfully implemented token.
this is my token:
{
"key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
Before I implement token in backend, it was working nice:
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
.then(function(response) {
$scope.contacts = response.data;
});
};
But, now I am not getting how can I implement this token here
Can anyone help me in this case?
Try to use this. You need to attach the token in the headers.
$http({
url : "http://127.0.0.1:8000/api/v1/contact",
method : 'GET',
headers : {
'Content-Type' : 'application/json',
'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
}).then(function(response){
$scope.contacts = response.data;
});
Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default

CORS error while sending request from Browser to play server even after sending CORS header

I have a REST API developed using Play Framework/Java and front end developed in Angular JS.
I am trying to call a POST method fron the Angular Client to the server using the following code:
$scope.login = function () {
console.log('login called');
var loginURL = 'http://localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
$http({
url: loginURL,
method: 'POST',
data: loginInfo,
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.greeting = response.status;
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
This is the code at my server:
public Result doLogin() {
ObjectNode result = Json.newObject();
result.put("status", "success");
return ok(result).withHeader("Access-Control-Allow-Origin", "*");
}
And this is the application conf file:
#allow all hosts.
play.filter.hosts {
allowed = ["."]
}
#allow CORS requests.
play.filters.cors {
allowedOrigins = ["*"]
}
Yet even after enabling CORS, I am getting error in console in both Firefox and Google Chrome:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
ERROR: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:9000/login","data":{"email":"xxx","password":"xxx"},"headers":{"Content-Type":"application/json","Accept":"application/json, text/plain, /"}},"statusText":""}
I do know that the server is sending the correct response and the correct header because when I do the POST from Postman, I can see the response and also the headers containing {"Access-Control-Allow-Origin", "*"} in Postman.
So then, what could be the problem? Is there something I am missing from the Client side?
The difference between POSTMAN request and browser request is browser sends an OPTIONS request before the actual POST / GET request.
To be able to accept OPTION request with your play framework allowedHttpMethods = ["GET", "POST" ,"OPTIONS"]
for follow this link
Play Framework 2.3 - CORS Headers
This causes a problem accessing CORS request from a framework (like angularjs). It becomes difficult or the framework to find what was the options request for and take action properly.
For fixing your problem you will need to analyze how the options request going and how it's being interpreted and how to overcome. But in general, I suggest using "fetch" built-in request for this, which supports the promises so can be chained easily with angularjs code
so your code will look something like this
$scope.login = function () {
console.log('login called');
var loginURL = 'http://localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
fetch(loginURL, {
method: 'post',
headers: {
"Content-type": "application/json"
},
body: loginInfo
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.greeting = response.status;
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}

How to simulate curl command with Angular

I have this curl command that I would like to simulate with angular:
curl -k -F fieldName=#data.json -u username:Password url
At the moment I went about doing an angular post. However, I run into the problem of authentication. There is no parameter for me to put the user id and password.
Angular code:
$scope.postCall = function () {
$scope.ngResult = "clicked";
var paramsJson = {
"imessageIdT": $scope.messageIdT,
"ilobT": $scope.lobT,
"iregionIdT": $scope.regionIdT,
"iassetClassT": $scope.assetClassT,
"additionalInfoT": $scope.additionalInfoT
};
var config = {
paramsJson: paramsJson
};
$http.post("WEBSITE", paramsJson, config)
.success(function (data, status, headers, config)
{
$scope.ngResult = logResult("POST SUCCESS", data, status, headers, config);
//$scope.ngResult = "Yes";
})
.error(function (data, status, headers, config)
{
$scope.ngResult = logResult("POST ERROR", data, status, headers, config);
//$scope.ngResult = "No";
});
};
Assuming basic authentication, not tested, this might work:
var username = "...", password = "***";
var config = {
headers: {
Authorization: "Basic " + window.btoa(username+":"+password)
},
method: "get", // or "post",
url: "destination.com"
};
$http(config).success(function(){
// on success
}).error(function(){
// on failure
});
The only thing I'm not certain about is window.btoa, if it's an RFC2045-MIME compliant variant of Base64, then you're good.
But my example is an over-simplification. Essentially, you should determine the authentication scheme supported by the server. It could be any one the following specified by IANA:
Basic
Bearer
Digest
HOBA
Negotiate
OAuth
Depending on the required scheme, you should compose the request header accordingly.
This depends on the api you are connecting to. Usually you would log and the server will return you an authentication token on the headers of the response.
1 Basic auth Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
2 Aoth2 Authorization: Bearer mF_9.B5f-4.1JqM
So you will need to add this header to your request:
$http.post("WEBSITE", paramsJson, angular.extend({}, config, {headers: {
'Authorization': token}}))
If the request is to another domain you should use jsonp.

Golang, cors and angularjs - header missing

I'm using rs/cors in my Go API to allow my Angularjs app to make direct requests. I've added the following code to configure CORS:
crs := cors.New(cors.Options{AllowCredentials: true})
n.Use(crs) //Negroni include
but I'm getting the No 'Access-Control-Allow-Origin' header is present on the requested resource message in the browser when I make a request.
My request looks like this:
var req = {
method: 'POST',
url: endPoint + version + method,
headers: {
'Authorization': 'Basic ' + btoa(':' + appId)
},
data: params
}
$http(req).
success(function(data, status, headers, config) {
callback(null, data);
}).
error(function(data, status, headers, config) {
callback(data);
});
How can I get round this?
Fixed it! I noticed that a few different headers were being sent with the request and I had to explicitly allow all of them.
AllowedHeaders: []string{"accept", "authorization", "content-type"}
I hope this helps someone.

Java Servlet not returning object to Angular $http.success method

I am learning Angular.js. I tried to search many existing questions but could not find one matching question or answer.
I am sending a GET request to a java servlet and expecting an object from it. Here is the angular $http GET request
$http({
method:'GET',
url : '/JSONWebApp/json/?fqn=' + $scope.fqn
}).
success(function(data, status, header, config){
console.log('Success');
console.log("data - "+data);
console.log("status - " + status);
console.log("header - " + header);
console.log("config - " + config);
}).
error(function(data, status, header, config){
console.log('Error');
});
On java servlet, here is what I write in doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Incoming Request URI : " + request.getRequestURI());
**User user = new User();
request.setAttribute("user", user);
RequestDispatcher view = request.getRequestDispatcher("/html/index.html");
view.forward(request, response);**
}
When the response is returned from this servlet, it goes to success of $http service in angular side. From where I will get the user object which I sent from server.
When I add the console.log to print the data, it prints the /html/index.html contents which is where I am forwarding.
Based on my research, my angular code is correct but I am not setting things correctly in java servlet.(Does this help - How to access json return values in angular.js action success callback)
Thanks in advance.
Add the following line to the $http object:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
Use POST method instead of GET
method: 'POST'
So in the end, we came up with something like this:
myData = {"name": "zezinho", "pass": "123xxx"};
$http({
method: 'POST',
url: 'Login',
data: myData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
alert(data);
}).error(function () {
alert("login error");
});
You need to serialize your User object into a JSON string and put that in the response body. A library like Jackson can help but before you add that in and confusing yourself more just serialize it into a JSON string yourself. Don't forget to set the Content-Type header.

Resources