how to add access token in angularjs http - javascript

i am new in developing a website using angularJS as my client-side and i am trying to access my JSON thru API call with $http.get method for angular.
my issue is that my API call requires an Access Token. i always get this error whenever i try to refresh my page.
XMLHttpRequest cannot load http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.
i am currently using this code to fetch my data.
myApp.controller('loginCtrl', function($scope, $http) {
$http.get("http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores")
.then(function(response) {
$scope.names = response.data.records;
});
});
how do i insert an access token on the $http.get method.

It depends on how your API get this access token. The most popular option is to just add specyfic header to your request
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Authorization': 'access token'
},
}
$http(req).then(function(){...}, function(){...});
you can also add it globally
module.run(function($http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});
or by using Angular interceptors
http://www.diwebsity.com/2015/12/17/interceptor-in-angular/

You are running into a SOP issue that is described here https://en.wikipedia.org/wiki/Same-origin_policy
You should have a look here:
Ways to circumvent the same-origin policy
Same origin policy
XMLHttpRequest Same Origin Policy

Related

CORS error in AngularJS app

I am getting following error when I try to make a POST request from my localhost app:
XMLHttpRequest cannot load https://www.xxx..yy/json/orders. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:9000', but only one is allowed. Origin 'http://localhost:9000' is therefore not allowed access.
This is my app structure in brief:
ctrl:
.controller('myCtrl', function ($scope,$http) {
var urlBase = "https://xxx/json/";
console.log("Hello...");
$scope.startDirectTransaction = function() {
console.log("startDirectTransaction form...");
$http({method: 'POST', url: urlBase + 'orders', headers: {
'api_key': 'xxx'}
}).then(function(response){
$scope.related = response.data;
console.log("Success!");
});
};
app:
<!-- begin snippet: js hide: false -->
You are trying to POST a data from your local app to a different domain. In general this is against CORS policy.
Solution for this issue is the domain which you are trying to post the data should allow via Access-Control-Allow-Origin
Read more about CORS in https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Cross domain issue in Google API's using angularJs

I am using following code to get the location details from the google API.
My code :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$scope.$apply(function(){
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true').then(function(res){
alert(res.data);
});
});
});
}
When I try this code I am getting the Cross domain Error.
My Error:
XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?latlng=8.5663029,76.8916023&sensor=true. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Please suggest to solve this issue
You're sending an Authorization header ... which causes a CORS preflight check, and google doesn't like the Authorization header
you need to remove this header from the API call
see if this helps
$http.get("your long url", {headers: {Authorization: undefined}})
obviously I've replaced the actual url for readability
I've also seen the following suggestion
$http( {
method: 'GET',
url: 'someurl',
headers: {
'Authorization': undefined
}
}
)
so, rather than using the $http.get "shortcut", use $http "general" request format
I had the same issue; I was using the satellizer module for authentication.
https://github.com/sahat/satellizer
As it says on the FAQ section:
"How can I avoid sending Authorization header on all HTTP requests?"
I did:
$http({
method: 'GET',
url: 'your google api URL',
skipAuthorization: true // `Authorization: Bearer <token>` will not be sent on this request.
});
And it solved my problem; maybe you are using a third party module that modifies the header.
I can't answer in the threat of the response i want, but
Maybe your are using Interceptors in your AngularJS application, so your request is modified some time later after your configure the:
{headers: { Authorization: null } }
I'm doing more research to overcome this. I'll post my finds later.
[Edit] Wed Jul 13 2016 21:38:03 GMT-0500 (CDT) [/Edit]
My solution to this, is going with straight Javascript, in that way my petition does not is intercepted by Interceptors from the $http Service and does not have the Authorization header.
So, maybe this help someone.
Cheers!

CORS blocks LinkedIn share API

I try to post new content using LinkedIn share API through JavaScript from AngularJS application as given below.
var xml = "<share><comment>" + content + "</comment><visibility><code>anyone</code></visibility></share>";
var req = {
method: 'POST',
url: 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=' + account.token,
headers: {
'Content-Type': 'text/plain'
},
data: xml
};
$http(req).success(function(data) {
console.log(data);
console.log('published to linkedin');
}).error(function() {
console.log(arguments);
console.log('failed to publish to linkedin');
});
I can successfully POST this data. However the browser blocks the response from being read because the response doesn't have an 'Access-Control-Allow-Origin' header.
But, I have given the http://localhost:3000 and 'https://localhost:3000' domains in LinkedIn application settings.
And the request/response in Chrome looks like this.
Any thoughts on how to be able to read the response and not let the browser block it?
I think the problem is the missing Access-Control-Allow-Origin header in the LinkedIn API response?
Looks like LinkedIn's REST API doesn't support CORS. They suggest to use REST API from the backend and not from browser. JS-SDK must be used from the browser.
https://developer-programs.linkedin.com/forum/cors

CORS issue with ASP.net Identity

I am working on an angular.js project with one of my friends, and we are running into a specific CORS (cross origin request) issue. The server is a Microsoft ASP.NET restful API, and I am using angular.js with Node.js.
We enabled CORS on the server side, and are able to get responses for everything else, accept the user login, which we are using ASP.NET Identity with. We always get the same error which I will post bellow, as well as the POST from the Client side. So basically my question is, does any one have an idea on how to fix this? Thanks!
XMLHttpRequest cannot load http://lectioserver.azurewebsites.net/api/v1/accounts/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost' is therefore not allowed access. The response had HTTP status code 400.
function login(username, password) {
var innerconfig = {
url: baseUrl + "/api/v1/accounts/login",
data: {
username: username,
password: password,
grant_type: "password"
},
method: "POST",
headers:
{
'Accept': 'text/json'
}
};
return $http(innerconfig).then(onSuccess, requestFailed);
function onSuccess(results) {
if (results && results.data) {
$rootScope.access_token = results.data.access_token;
return results.data;
}
return null;
}
}
Try to set the content-type in the headers, this might fix the issue
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
This usually happens because app that provides you token starts before CORS initiates.
Fixing it is very easy. You just need to go to IdentityConfig.cs and inside that there is function called as
public static ApplicationUserManager Create
(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
Insert this following line of code there
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
This will enable CORS for Token request.
But problem is when we do this other normal requests will start throwing error since we have granted access origin * twice. Once in identiy and other in cors.
if you run into this error use this if statement on cors code in identity config you just pasted.
if(context.Request.ContentType == "text/plain")

Angularjs error when trying to read title from url

I'm using AngularJS along with Node.js and I'm trying to read title from a specific url
I have something like this:
App.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
//Remove the header used to identify ajax call that would prevent CORS from working
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
And I try to read urls title with:
$http({ url:$scope.url,method:"POST", headers: {'Content-Type': 'application/x-www-form- urlencoded'}}).success(function(data){
console.log(data);
});
But I get NetworkError: 405 Method Not Allowed and/or Cross-Origin Request Blocked:....
It doesn't matter what your client-side code is, you'll need to enable CORS on the server side to allow Cross-Origin requests.

Categories

Resources