cookie does show in browser however cannot be accessed using $cookie.get('io'). What am I missing. I also tried $timeout with 5 seconds delay. I tried to see in headers() but this token does not show there.
Code:
$http({
url: 'http://localhost:8081/api/v1/login',
method: 'POST',
data: $httpParamSerializerJQLike({
username: username,
password: password,
REQUEST_TYPE: requestType
}), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).success(function (data, status, headers, config) {
//10 seconds delay
$timeout( function(){
var favoriteCookie = $cookies.get('io');
alert(favoriteCookie);
}, 5000 );
//time
var time = 0;
//timer callback
var timer = function() {
if( time < 5000 ) {
time += 1000;
$timeout(timer, 1000);
}
}
//run!!
$timeout(timer, 1000);
//console.log(response.headers('set-cookie'));
callback(response = { success: true });
}).error(function (data, status, headers, config) {
callback(response = { success: false });
});
Please check that the cookie you are trying to get is not tagged as httpOnly.
When you tag a cookie with the HttpOnly flag, it tells the browser
that this particular cookie should only be accessed by the server. Any
attempt to access the cookie from client script is strictly forbidden.
Of course, this presumes you have: A modern web browser. A browser
that actually implements HttpOnly correctly.
it was autogenerated cookie. the cookie which i was trying to access did not appear in the browser. I had to make some code modifications in angularjs to get the cookie into browser. I had to include a parameter "withCredentials:true," in the http request. As soon as I did it my cookie appeared in the browser. Now my http request look like this.
$http({
url: 'http:localhost/login',
method: 'POST',
data: $httpParamSerializerJQLike({
username: username,
password: password,
REQUEST_TYPE: requestType
}), // Make sure to inject the service you choose to the controller
withCredentials:true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;
}
}).success(function (data, status, headers, config) {
callback(response = { success: true });
}).error(function (data, status, headers, config) {
callback(response = { success: false });
});
}
Related
I make an https request to outer service in http://transltr.org/.
var reqUrl = "http://transltr.org/api/translate?text=dog&to=he";
var deferred = $q.defer();
$http.get(reqUrl).then(function(response) {
deferred.resolve(response);
alert("sada");
},function (error) {
deferred.reject(error);
});
return deferred.promise;
rrsponse is 200, and I get data:
but error alert fired. There is a way to get this data?
I also see error in console :
XMLHttpRequest cannot load http://transltr.org/api/translate?text=dog&to=he. The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://myDomain.co.il' is therefore not allowed access.
I also tried this version(in this case, no response at all):
var reqUrl = "http://transltr.org/api/translate";
var params = {
to: to,
text: text
};
var deferred = $q.defer();
var request = {
method: 'GET',
url: reqUrl,
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*'
},
params: params
};
$http(request).success(function (data) {
deferred.resolve(data);
}).error(function (error) {
deferred.reject(error);
});
If you're using Chrome on Windows, do the following to disable the CORS filter.
Exit chrome. Press Windows Icon then letter R as you keep windows key down. Paste the command below on the resulting box and press enter.
chrome.exe --user-data-dir="C:/Chrome dev session"
--disable-web-security
This will open Chrome with websecurity disabled(no CORS filter). Now reload your app on this Chrome window and let me know of any resulting exceptions. This is to aid you achieve what you want to, but you have to handle CORS in your API.
you cant mix Javascript and PhP variables
var deferred = $q.defer();
In my AngularJS app I am sending HTTP GET request as below.
MyService.HttpReq("testUrl", "GET", null);
HttpReq Method is defined in a service and implemented as below:
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: postData,
headers: {
'Content-Type': 'application/json',
}
}).success(function(response)
{
console.log("Success: "+JSON.stringify(response));
}).error(function(data, status)
{
console.error("Error");
});
}
First of all is this the right way of sending HTTP request in AngularJS?
The problem that I am facing is, some times I get cached data as response and HTTP request is not hitting the server. what can be the issue?
UPDATE
As per the comment and answer I have updated my HTTP request code as below, but still getting same issue.
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: payload,
headers: {
'Content-Type': 'application/json',
'Cache-Control' : 'no-cache'
}
}).
then(
function(response)
{
var data = response.data;
console.log("Success: "+JSON.stringify(data));
},
function(response)
{
var data = response.data || "Request failed";
var status = response.status;
console.error("Error: "+JSON.stringify(data));
}
);
}
IE Browsers will catch ajax get requests even if we add cache control headers to the response. Only way i found to solve the issue is to add some random parameter to the request. Please make sure the api have no problem even if you send extra parameters
MyService.HttpReq("testUrl?ts=" + Date.now(), "GET", null);
Just add cache: false attribute to config object.
https://docs.angularjs.org/api/ng/service/$http#caching
Also you can add header: 'Cache-Control' : 'no-cache'
I am using $http to post data to server.
There are two OPTIONS requestMethod calls before making a POST request.
However, the POST request is not made sometimes.
As I am updating html on return of this call, the page hangs.
$http({
url: scope.Settings.url,
method: "POST",
data:data,
withCredentials: true
}).then(function (data, status, headers, config) {
setBusyState(false);
scope.rModel = scope.search;
scope.Results = data.data;
}, function (data, status, headers, config) {
scope.Results = [];
setBusyState(false);
});
EDIT: This does not happen always. Only a few times.
This appears to happen only in Chrome, whereas it is fine in IE
This is a known issue with AngularJS where it caches the subsequent http requests so if you have multiple http requests lined up you would sometime experience that some of the calls are not actually made.I have mainly seen this issue of aggressive caching in IE.
To overcome this issue you need to apply some sort of global settings which will prevent the http requests from getting cached.The ideal place of doing this in angular is $httpProvider.
Basically you are setting different header parameters with the appropriate values.
Related code from app.config
appConfig.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.cache = false;
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = <set a time>;
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}
]);
What angular does in chrome is, it makes OPTIONS request.
These Pre-Flight OPTIONS requests are a way of asking permissions for the actual request, before making the actual request.
So, as a work around, adding headers to the request solves the problem.
$http({
url: scope.Settings.url,
method: "POST",
data: data,
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}).then(function(data, status, headers, config) {
setBusyState(false);
scope.rModel = scope.search;
scope.Results = data.data;
}, function(data, status, headers, config) {
scope.Results = [];
setBusyState(false);
});
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.
I've got a simple node.js backend build on Restify with OAuth2 authorization (restify-oauth2 plugin).
I've got a problem requesting a token. When I call POST method with my REST client, everything works correctly and I get access_token and token_type.
The problem occurs when I try to do the same thing in my frontend aplication made in Angular.
Here's my code:
var req = {
method: 'POST',
url: 'http://localhost:8080/token',
headers: headers,
data: {},
params: {grant_type: "client_credentials"}
};
$http(req).success(function(data, status, headers, config){
console.log('success');
}).error(function(data, status, headers, config){
console.log('error');
});
So as you can see, grant_type parameter is provided. But still the server responds with:
{"error":"invalid_request","error_description":"Must specify grant_type field."}
And here's devtools screenshot:
How do I need to change my request to make it work?
I finally solved it. The thing is that grant_type field must be passed inside a request body, not in the parameters.
Working request code:
var req = {
method: 'POST',
url: 'http://localhost:8080/token',
headers: headers,
data: "grant_type=client_credentials"
};
$http(req).success(function(data, status, headers, config){
console.log('success');
}).error(function(data, status, headers, config){
console.log('error');
});