localhost is appending to RequestURL while $http.post using angularjs - angularjs

I am using json-server(https://github.com/typicode/json-server) as a mock server.My json server runs # 127.0.0.1:3001. When i am trying to post data to that json server using $http.post() from my application which runs at localhost:3000. Its posting like http://localhost:3000/127.0.0.1:3001/tasks/....
When i look some other posts they were suggesting to enable CORS at server end. But i donno how to enable CORS to json server. Can any1 help me out for this.
Code:
return $http.post(config.baseURL+"/tasks"+app,{headers: {'Content-Type': 'application/json'} })
.then(success)
.catch(fail);
Kindly help. config.baseURL has 127.0.0.1:3001.
PFA Screenshot too
Looking forward for help from techies...

Related

Using https rather than http in angular to get data from server

My application has the following architecture,
An angular 1.5 application has a service which sends request to one of endpoints on server.
The request is received by an nginx server if it is an http request it is redirected to https server.
Then the nginx server redirects my request to upstream node server.
In angular I use the http service to send get and post request.
I don't know if my request along with the data are travelling encrypted by https protocol or as plain text by http protocol from angular to server and back.Can someone please clarify what is going on, the data might contains personal details of user and it is important that it is encrypted.
This question asks the same but is not answered properly.
Thank You.
You can force $http to use HTTPS simply by ensuring that your URL is formatted correctly.
var req = {
method: 'POST',
url: 'https://localhost/api/v1/users', // note: https specified
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
angularjs docs - $https

angular ngresource can't send headers

I'm new to the angularjs/ionic mobile app development. I'm using Parse REST api to store data and already hosted Parse server in Heroku. Tested with postman chrome extension and everything working fine. The problem that i'm facing right now is my angular-resource seem look like not sending any headers used to authenticate with parse to the server.
angular.module('starter.services', ['ngResource']).factory('Session', function ($resource) {
return $resource('/restapiurl', {}, {
get: {
method:'GET',
headers:{'X-Parse-Application-Id':'XXX', 'X-Parse-REST-API-Key':'XXX'}
}
});
});
Need an advice/guide to make my code work perfectly. Any help would be appreciate. Thanks in advance
UPDATE: I'm managed to send custom headers to the server. The workaround is to use $httpProvider.defaults.headers.common with the key and value inside module.config

Angular $http.put packet not in correct format

I'm kind of new to angular, and it's the first time I'm using $http.put.
My problem is when I send the packet, it won't include the data (json object), and the PUT is a header(?).
This is what my code looks like:
app.controller('StatusController',['$http', function($http) {
this.updateComment = function (eventid, comment) {
var requestData = {"event-id":eventid, "new-comment":comment};
$http({
method: 'PUT',
url: "http://172.18.212.59/event",
data: requestData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
So I used Fiddler to generate a PUT request to the server, and it worked. so I looked at the packets, trying to understand where the differences come from...
Here are the results:
Packet generated by Angular - Not working
Packet generated by the Fiddler Composer - Working
Also I've tried using:
$http.put(url, requestData)
But that didn't work either... My GET requests work perfectly fine! And they look like the packet that does work...
Has anyone encountered this problem before?
Appreciate your help!
OPTIONS verb is used when doing cross domain requests. Basically you need to enable cross domain requests on your server side code. The GET request works cause it isn't protected by cross domain restrictions and Fiddler works cause cross domain requests comes into picture when making XHR requests from browser. If you look into the response to the OPTIONS request you will probably find something saying cross domain request not allowed.

angularjs preflight request fails to load data

I am developing a single page application using Angularjs framework.
inside my homeController i use a service call as below
$http({
method: 'POST',
url: 'http://localhost:1530/api/Profile?username=sa&password=da',
data: { Email: "dmytest#test.com", Password: "saas" },
headers: {'Content-Type': 'application/json'}
}).success();
The problem is that when i am making a api call the browser initiates a preflight request with method options instead of post.
Server responds with all required headers.But the actual call is not done.Preflight request initiates only when using "Content-Type:application/json".
I am posting Json data to server.
Is there any way to either prevent the preflight request nor making a successfull api call?
It is working fine on mobile as well as on ajax call.
Thanks in advance.
Depending on you browser, try forceCORS
Chrome: https://chrome.google.com/webstore/detail/forcecors/oajaiobpeddomajelicdlnkeegnepbin?hl=en
Firefox: http://www-jo.se/f.pfleger/forcecors
Also ensure you have enabled CORS on your Server side. I reference here some examples. Please find out what you platform offers:
JAX-RS: http://www.developerscrappad.com/1781/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-cors-on-rest-how-to-make-rest-apis-accessible-from-a-different-domain/
JAX-RS: http://cxf.apache.org/docs/jax-rs-cors.html
Nodejs: http://www.bennadel.com/blog/2327-cross-origin-resource-sharing-cors-ajax-requests-between-jquery-and-node-js.htm
Hope this helps.

AngularJS: $http.post throws error

I am using Request Bin to post some data. In my controller, I have the following code:
$http.post('http://requestb.in/redacted', fooBar).
success(function(data) {
$scope.fooBarPostedSuccess = true;
}).
error(function(err) {
console.log("Error while posting to Request Bin");
console.log("Error Info : " + err);
});
This is triggered by means on a button on the UI. Now when this gets triggered, the data is not posted to Request Bin and I get this error:
XMLHttpRequest cannot load http://requestb.in/redacted.
Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
How do I post data to request bin through an AngularJS controller? Also, what does the above error mean?
EDIT : I wish to add here that I am using Node.js with AngularJS. Is this something to do with Node perhaps?
Ah yes... you are dealing with cross-domain scripting issues. This is not an AngularJS problem, but a browser security limitation and a VERY common friction point.
You cannot POST/PUT/DELETE to another domain (different from the one which is hosting -- localhost in your case) without doing some Cross-Origin Resource Sharing (CORS). You are limited to GET for a cross-domain HTTP request.
You have two options:
See if your API supports any cross-domain capabilities. This might be via CORS or it might be via an overloaded GET API or JSONP.
Proxy requests through your server. Since you are using Node.js, proxying REST through your server is extremely simple... you just need to set up a route handler (like /api/redacted) in your Node.js server and then make a new request to your actual API server with something like Restler (NPM package) and return the result back to your client.
Hope this helps!
EDIT:
Your API supports JSONP (Your API Docs). You should be able to use Angular's JSONP function to access your API's JSONP capabilities. (Angular.js JSONP docs).
Since you want to be able to POST to the service, you will need to use the second approach.
CORS allows both GET and POST
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
http://www.w3.org/TR/cors/
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Now, that that's out of the way...
I too have found that angular's $http won't let me POST cross domain. I was suspicious about that though because I have jquery ajax calls in other projects that can post cross domain just fine. So, I swapped my $http POST with $.ajax POST and that worked.
// $http({
// url: url,
// method: "POST",
// data: data
// })
// .success(successCallback)
// .error(errorCallback)
// ole reliable
$.ajax({
type : "POST",
url : url,
data : data,
success : successCallback,
error : errorCallback,
cache : false,
dataType : 'json',
})
You can use PutsReq instead of RequestBin. PutsReq supports CORS.

Resources