Send cookies in ajax angular - angularjs

I want to send the document cookie in the http call in angular.
I have already used withCredentials but it can only send the browser level cookie.
I also use the cross domain ,but it is not working fine.
Below is the code which I am using.
$http({
method: 'GET',
url: url,
xhrFields: { withCredentials: true },
crossDomain: true,
header:{ 'SHOPSESSIONID' : sessionStorage.getItem("SHOPSESSIONID") }
}).success(function(data){
return data;
}).error(function(data){
return data;
});

use $httpProvider in config phase:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}])
and you could give up the xhrFields and crossDomain proporties
btw, angular uses then instead of success, and catch instead of error. (that is the promise syntax)

Related

AngularJS access $http on onNotification event PushNotification cordova plugin

I'm using the plugin https://github.com/phonegap-build/PushPlugin/ with Angular 1.3 and I need to send the regid to server when receive "registered" event.
The problem is that I don't have $http object to call my server on this context. How can I achieve that, please?
function onNotification(e){
if(e.event == "registered"){
var req = {
method: "POST",
url: "http://myurl.com/?var="+e.regid
};
$http(req).success(function(data){
alert(data);
});
}
}
I just learned how to inject $http into the event method:
$http = angular.injector(["ng"]).get("$http");
Change $http call as follows, .success is deprecated.
$http({
method: "POST",
url: "http://myurl.com/?var="+e.regid
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
alert(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Ref. : https://docs.angularjs.org/api/ng/service/$http
Regards.

Can not get response cookie from angular $http post using ionic

I am sending a post auth request from my localhost to a remote server to get response cookies returned by server(using ionic proxy to solve CORS). From chrome network inspector, I can see the response cookie has been returned from server. However, I am not able to access it from $http post response. I try almost everything from other posts and I still can not get the cookie. What I have tried
I use ngCookie and $timeout combination. Basically I get an empty object when I use $cookie.getAll() which I assume the cookie is not there
I also set withCredentials to true
I also tried headers.get('set-cookie')
My angular version is 1.5.3. Please help
Below is my code
angular.module('starter.controllers', ['ngCookies'])
.controller('DashCtrl', function($scope, $http, $cookies, $timeout) {
$http({
method: 'POST',
url: '/api/User/Authenticate',
data: {
Username: 'xxx',
Password: 'xxx'
},
withCredentials: true
}).then(function(response) {
$timeout(function() {
console.log($cookies); // return {}
console.log($cookies.getAll()); // return {}
});
}, function(response) {
});
})
Here is the server response

add config in angular resource

I am using http-auth-interceptor for authentication. In http-auth-interceptor, I use the following way to login:
var data = 'username=' + encodeURIComponent(user.userId) + '&password=' + encodeURIComponent(user.password);
$http.post('api/authenticate', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
ignoreAuthModule: 'ignoreAuthModule'
})
ignoreAuthModule is used to tell ignoreAuthModule that this login method will be ignored by the auth interceptor.
Now, I have some request with $resource, like:
.factory('SomeDataService', function ($resource) {
return $resource('api/some/data', {}, {
'get': { method: 'GET'}
});
})
I want SomeDataService.get() is also ignored by the auth interceptors, because I need to control the 401 error by myself.
So, my question is, is there any way for ngResource that I can set config like that in $http.
[update based on comment]
I have listened the login-required event:
$rootScope.$on('event:auth-loginRequired', function (rejection) {
$log.log(rejection);
// I need to get the request url and for some specific url, need to do something.
$rootScope.loginPopup();
});
But the 'rejection' parameter has no context data of request I need. I need to get the request url and check, for some specified url, I need to do something.
After checking the document of ngResource, I got the solution as below:
.factory('SomeDataService', function ($resource) {
return $resource('api/some/data', {}, {
'get': { method: 'GET', ignoreAuthModule: 'ignoreAuthModule'}
});
})
Just add the config item as above. It will be equivalent ad:
$http.post('api/some/data', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
ignoreAuthModule: 'ignoreAuthModule'
})
ngResource module is build on top of $http.Hence it is not possible to configure all the stuffs you can do with $http in $resource.I think the below link will be guide you to have a clear understanding on $http and $resource

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 can you test for http config options in AngularJS?

In this service method I want to test for the presence of the skipAuthorization setting.
var register = function (registration) {
logout();
return $http({
url: apiUrl + 'api/account/register',
method: 'POST',
data: registration,
skipAuthorization: true
});
};
Using $httpBackend, I can inspect the data and the headers, but I can't find any documentation related to the optional config object.
Thanks!
UPDATE:
I'm not thrilled with the solution below, but it does test the scenario in a round-about way.
it('should flag the interceptor to skip authorization', function () {
spyOn(my_store, 'get').and.returnValue('foo');
service.register();
http.expectPOST(url, undefined, function (headers) {
//If we don't skip authorization, this header would be "Bearer foo"
return headers['Authorization'] === undefined;
});
http.flush();
});
This works because if I don't set skipAuthorization to true, I will see a bearer token on the request headers. It relies on the fact that my interceptor pulls the token out of local storage, which I have mocked with a Jasmine spy (my_store).

Resources