$http response returns the entire index.html - angularjs

I have site.com.
Each request is redirected here (so 'site.com/book', 'site.com/settings' ecc.. point to 'site.com')
Then I have site.com/api/ where 'site.com/api/user', 'site.com/api/library/' ecc... are redirected.
I'm trying to use $http of AngularJS to request a JSON object to site.com/api.
On success, I receive status 200 but the response is the text/html of 'site.com/index.html'.
The headers sent with the request are:
Accept: "application/json, text/plain, /"
Content-Type: application/json;charset=utf-8
I tried to debug site.com/api/ with the app postman and it works as expected since I receive the correct JSON object.
I don't know if it is a problem of some .htaccess rule or the $routeProvider of AngularJS...
(I have a .htaccess file in 'site.com' and another one in 'site.com/api').
But I could be completely off the road. Maybe someone can help? Thanks.
var config = {method: 'POST', url: 'site.com/api/', data: $scope.data};
$scope.login = function(){
$http(config)
.success(function(resp, status, headers, config){
console.log(resp);
})
.error(function(resp, status, headers, config){
console.log(status);
});
};

Ok I tried again with a clearer mind this morning.
It seems that I was missing the http part of the url site.com/api/.
So it can work both with
var config = {method: 'POST', url: 'http://example.com/api/', data: $scope.data};
or
var config = {method: 'POST', url: '/api/', data: $scope.data};

Related

$http post multipart/form-data boundary not set

I am setting the boundary for the below post call but on chrome the boundary looks different from the one I set. how do I get my custom boundary "--test" to show up on the request payload?
var url = '/site/apkUpload';
var deferred = $q.defer();
console.log(formdata);
$http.post(url, formdata, {
processData: false,
headers: {'Content-Type': "multipart/form-data; charset=utf-8; boundary='--test'",
'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
'x-access-token': token,
'cache-control': 'max-age=0'}
})
.success(function (response) {
deferred.resolve(response);
})
.error(function (reject) {
deferred.reject(reject);
});
return deferred.promise;
Request payload on chrome:
------WebKitFormBoundaryB5LjM2a6Qly3Xruj
Content-Disposition: form-data; name="packageName"
helo1
------WebKitFormBoundaryB5LjM2a6Qly3Xruj
Content-Disposition: form-data; name="name"
......
Thanks a lot!
I can interpret your question in 2 ways:
You are talking about why you are not getting ------WebKitFormBoundaryB5LjM2a6Qly3Xruj in the POST request header, which you are getting in the request payload. I had the same issue while sending a multi-part formdata using $http.post (also I was using FormData).The solution to this is using $http(config).To my understanding $http.post underlying uses $http() itself to generate XMLHttpRequest object, which should run the multipart/form-data encoding algorithm to set the multipart boundary in payload and the header as well. In $http.post, it seems whenever you give a custom config object it overwrites the header generated by the algorithm. This answer is also helpful.
If you just want to add a custom multipart boundary in the content-header, then you can achieve that by add a tranformRequest function in the config object:
var url = '/site/apkUpload';
var deferred = $q.defer();
console.log(formdata);
$http.post(url, formdata, {
processData: false,
transformRequest: function (data, headers) {
var boundary = yourCustomLogic();
headers()['Content-Type'] = 'multipart/form-data;charset=utf-
8;boundary=' + boundary;
},
'Accept': ...,
'x-access-token': token,
'cache-control': 'max-age=0'
})
.success( function () {...});

Angular $http.post returnd empty error

I am using angular JS to send some data to nodejs server.
When I use, curl, I get back the data I send (correct result):
curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" 'http://127.0.0.1:3000/s?table=register_rings&uid=1'
> {"MyKey":"My Value"}
However, when I use angularjs service, error occures.
.factory('RegisterRingsService', function($http, $q) {
// send POST request with data and alert received
function send(data, uid) {
$http({
method: 'POST',
url: 'http://127.0.0.1:3000/s?table=register_rings&uid=1',
data: '{"MyKey":"My Value"}',
headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin":"*"},
responseType: 'json'
}).success(function(data, status, headers, config) {
alert('success', data, status);
}).error(function(data, status, headers, config) {
alert('error' + JSON.stringify(data) + JSON.stringify(status));
}).catch(function(error){
alert('catch' + JSON.stringify(error));
});
}
return {send : send};
})
The error is following:
{"data":null,"status":0,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://127.0.0.1:3000/s?table=register_rings","data":"{\"MyKey\":\"My Value\"}","headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Accept":"application/json, text/plain, */*"},"responseType":"json"},"statusText":""}
I suspect that I should insert CORS headers, but I am not sure how to do that.
Any help would be appreciated
The problem is how you are transmitting the data over to server. This is because jQuery and Angular serialize the data differently.
By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages — notably PHP — do not unserialize natively.
To workaround this AngularJS developers provided hooks into the $http service to let us impose x-www-form-urlencoded.
$http({
method :'POST',
url:'...',
data: data, // pass in data as strings
headers :{'Content-Type':'application/x-www-form-urlencoded'} // set the headers so angular passing info as form data (not request payload)
});
Please read this post for a working solution:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

"Must specify grant_type field" error when getting Oauth2 token

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');
});

Not getting response from Gmail API (Users.messages: send) -- running on mobile device via IonicFramework + AngularJS

I am able to send emails successfully using GMail's API with no issues. The receiver gets the email after a few seconds, but the app doesn't get a response from GMail (i.e., threadid, id, etc...) described here.
I'm running this on a mobile device via IonicFramework w/c uses angularJS by the way. What could be wrong?
$http({
method: 'POST',
url: 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart',
headers: {
'Authorization':'Bearer '+ access_token,
'Content-Type': 'multipart/mixed; boundary="foo_bar_baz"'
},
data: emailStr
})
.success(function(data, status, headers, config){
console.log(data);
})
.error(function(data, status, headers, config){
console.log(data);
});
emailStr contains the base64-encoded message.
This is how the request details look like:
Request URL: https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart
Request Headers
Accept:application/json, text/plain, */*
Authorization:Bearer <<token here>>
Content-Type:multipart/mixed; boundary="foo_bar_baz"
Origin:file://
User-Agent: <<User agent data>>
Query String Parameters
uploadType:multipart
Request Payload
--foo_bar_baz
Content-Type: application/json; charset="UTF-8"
{"raw":"<<encoded string>>"}
--foo_bar_baz--

Paypal API with angular and cURL

Currently I'm working with paypal API and flowing with this document make your first call.
When I sent a request through angular $http to paypal, I got a Status Code 415. It's seems like I missed something, does anyone can help me? :)
here is my code
$http({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'POST',
headers: {'Content-Type': 'application/json',
'auth-token': 'EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp',
'Accept-Language': 'en_US'
},
data: { 'grant_type': 'client_credentials' }
}).success(function (data, status, headers, config) {
console.log(data)
}).error(function (data, status, headers, config) {
console.log(data)
});
Referring to the Paypal doc
Tip: If you're using Windows, we recommend you make cURL calls using a
Bash shell. If you're not using cURL calls, set the content-type to
application/x-www-form-urlencoded for this request.
Try set the content_type as application/x-www-form-urlencoded

Resources