I am developing a small application use angularJS. The html pages are local file which will not deploy on web server. I defined a service module which will call the remote webapi to get the json data, however my success callback not be invoked.
$http({ method: 'GET', url: remoteServiceUri }).
success(function (data, status) {
var response = data;
}).
error(function (data, status) {
var error = data;
});
it always call into the error method. how can I resolve this issue please?
I can confirm that the service api work fine, as I tried deploy the page and webapi on the same site, in this case, it works.
is this caused by the cross domain or any configuration required?
Thanks.
You need to configure your remote web service to handle the preflight OPTIONS request.
Your web service must add the following headers to the response of the preflight OPTIONS request as well as the actual request:
{
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type"
}
You can find details about what which headers are required, and what do they mean here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
If you are using Apache, you could use proxypass to redirect requests. This way your angular app talks "locally" with your apache server, and it will pass the request to a different domain.
For example, in your httpd.conf set:
ProxyPass /foo http://foo.example.com/bar
In your angular app call
$http({ method: 'GET', url: "/foo/action" }).then(...);
Your apache will translate "/foo/action" to "http://foo.example.com/bar/action".
Bye bye cross domain issues!
For more info, see apache proxy module
Related
I have a Https url and want to send request to get data from that URL , scenario 1:
from my browser If I hit the Url i get the response whereas from my Angularjs App I get always an error 401 , but if I hit the Api from browser I always get the correct response
for security reasons I couldn't use Url here but what I want is to:
$http({
method: "GET",
url: "https://urlAdresss/",
headers: {
"Accept-Language": "en-US, en;q=0.8",
"Content-Type": "application/json;charset=UTF-8"
},
}).then(function (_response) {
console.log(_response
}
I always get unauthorized I am network as well as On console any help will be greatly appreciated ,
but If I hit the same Url from browser I get the response It means the backend is working fine
I think I am missing something in my get request that's why getting the error
It seems a CORS (Cross-Origin Resource Sharing) issue.
In AngularJS side, you should use the following configuration in order for $http service to automatically send authorization headers to http requests.
var app = angular.module('app', [])
.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
});
And in backend you should specify explicitly allowed origins (eg. http://localhost:8888).
Also, note some points from here.
If you want to allow credentials then your Access-Control-Allow-Origin must not use *.
I'm writing an angularjs 1.5.0 application.
In this application i need to use $http to fetch image data to a blob.
i used the following code in my angular js controller:
$http({
url : 'https://myalcoholist-tuxin-com.s3.amazonaws.com/my-images/thumb_0000000001.jpg',
method : 'GET',
params : {},
headers : {
'Content-Type' : undefined,
},
responseType: "blob"
}).success(function(data, status, headers, config) {
}).error(function(data, status, headers, config) {
});
my website is at https://myalcoholist.com
I enabled cors in my s3 bucket using Bucket Explorer with the following parameters:
AllowedOrigin https://myalcoholist.com
AllowedHeader *
AllowedMethod GET
before settings the cors , i would get a preflight request error. after enabling cors I get
GET https://myalcoholist-tuxin-com.s3.amazonaws.com/my-images/thumb_0000000001.jpg 400 (Bad Request)
the pre-flight request, the OPTIONS method is sent and succeeds.
Request URL:https://myalcoholist-tuxin-com.s3.amazonaws.com/my-images/thumb_0000000001.jpg
Request Method:OPTIONS
Status Code:200 OK
Remote Address:54.231.114.146:443
but then the GET Request fails.
I tried to put an image on https://myalcoholist.com and then to try to get it with $http request and I got no errors. it seems that only trying to download from amazon's s3 is causing problems and I have no idea why!
the ACL is set for read. and browsing that file in the browser works.
any information regarding the issue would be greatly appreciated.
I'm developing a new Angular client which should communicate with my Node/Express server. I'm currently trying to develop the first step aka the login. This should be an http json post. It turns out that every single time I execute that post from the client to the server, the Node/Express server doesn't find the route for my path.
On the console log of the server, for my post json request I find following stacktrace:
OPTIONS /api/auth/facebook/mobile 404 274.092 ms - 1980
Node/Express side:
My route
app.post('/api/auth/facebook/mobile', authenticationHandler.handleFacebookMobileLoginRequest);
Body parser for json is defined:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
On the Angular client side, I do:
http({
method: 'POST',
url: 'http://192.168.1.101:3000/api/auth/facebook/mobile',
headers: { 'Content-Type': 'application/json; charset=UTF-8;' },
data: {fbToken: authResponse.accessToken}
})
.then(function (response) {
...
Fun facts:
Same route works fine when I call it from a Java app or and Android native app, like
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SERVER_URL + "/api/auth/facebook/mobile", params, jsonRequestListener, errorListener);
On my Angular client, when I change data with params then it works, the route is found...but I mean that doesn't make any sense. Moreover, I've got then a problem on the Angular client side, the answer isn't processed respectively the answer never land in the .then(... function. Which again works well in other clients.
Anyone got an idea, a clue or should I call Dr. Strange?
Possible browser preflighted request CORS issue?
Try using CORS module in Node.js server:
var cors = require('cors')
app.use(cors());
I am successfully using a curl request to authenticate a user on my Django project with Django-social-auth using a Facebook token to return a token for my personal site. Quite simply, I have a Facebook token and I am converting it to a Django token in return, but I am only accomplishing this feat using a CURL request. The framework I am using comes from Philip Garnero (1).
The CURL request - curl -X POST -d "grant_type=convert_token&client_id=&client_secret=&backend=facebook&token=" http://localhost:8000/auth/convert-token
The confusion comes when I am trying to do this using an AJAX request.
Is there something wrong with the way my ajax is setup? Do I need to get a csrf token to begin with before I can convert my facebook token to a authenticated Django token?
Update: I am getting a 400 error unsupported_grant_type while running my ajax request through a proxy. The request is the same request I have successfully executing in both a curl command and a Postman command.
Ajax Request:
$http({
url: "proxy/url/...",
async: false,
crossDomain: true,
method: "POST",
data: {
"client_id": "...",
"client_secret": "...",
"grant_type": "password",
"username": "...",
"password": "..."
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log("error status = " + status);
console.log(angular.toJson(data));
});
(1) - https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
I figured out the issue, but I cant point to the specific thing I did in order to get it working. I will instead write down everything I did in order to get a working system. My particular example was for an ionic app that used facebook authentication and converted the token to a django csrf token which I used to track users.
My setup: Django, Django rest-framework Social Oauth2 (Philip Garnero's setup), Django social auth, angular js, cordova facebook plugin, ionic (3rd party app that acts as the frontend) and finally a configured proxy service.
Steps: Number one, make sure to have a rest api system installed. I used Philip Garnero's api (1). Once I got the installable package from Garnero in place I had to configure an ionic proxy service. I used Ionic's tutorial to get it in place (2). That document is worth reading to understand the gist of cross domain requests. Finally, what I couldn't find without testing and researching around were the correct headers to attach to the ajax request. I ended up solving it using a very useful tool called Postman.
Here is a dumb example of that "confusingly difficult" request:
$http.post(Url, queryStringData,
{headers: {
'Accept': '*/*',
"cache-control": "no-cache",
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
console.log(data.access_token);
}).error(function(data, status, headers, config) {
console.log("error status = " + status);
console.log(angular.toJson(data));
});
Please comment if you have questions. I will do my best to clean up the original post and may consider a tutorial if others are having the same issues. I spent 5 hours trying to crack this one.
(1)- https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
(2)- http://blog.ionic.io/handling-cors-issues-in-ionic/
I am developing a cordova application. After login i need session id for all server call. For that i need to get session id from Set-Cookie header. In angular $http service didn't show Set-Cookie in response header. How i got the Set-Cookie?
$http({
method: "POST",
url: "http://localhost:3000/contacts",
data: JSON.stringify({'key':'value'})
}).success(function(res,status, header, config){
console.log(config, header);
}).error(function(err){
alert('Unautherized '+JSON.stringify(err));
});
Add an $http interceptor that reads the value from the cookie and sends it in every request. Cookie can be read with $cookies service. Example:
$cookie.get('session');
To use $cookies service don't forget to add ngCookies module as a dependency first.