using angular $http.post will not post to file - javascript

With the code below I keep getting a 404 error. the hello.json file is in the root and I can access it in the browser since it is at localhost:3000/hello.json
not too sure what I did wrong and why this wont write and just returns a 404 not found error.
on click of the button(in the html) that runs the update function I get the alert with the error callback.
angular.module('seakrat')
.controller('MainCtrl', ['$scope','$http', function ($scope, $http) {
$scope.update = function(course){
$http.post("/hello.json", {hello: "there"})
.success(function(data, status, headers, config) {
alert('nailed it')
})
.error(function(data, status, headers, config) {
alert(data + status);
});
$scope.course = '';
};
}]);

You cannot write to a file using angularJS, its a client side framework. You need to have a serverside language to do this job.

Related

angularJS sending OPTIONS instead of POST

Im stuck at this 2 days I can not find a solution.
When im doing an AngularJS POST it Sends OPTIONS in the header and returns error from the API the code looks like this nothing special.
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post(URL, JSON.stringify(data)).
success(function(data, status, headers, config) {
alert(data);
error(function(data, status, headers, config) {
console.log("Error");
});
CORS is enabled on the API it has the Headers, when i do POST with fiddler or POSTMan in Chrome it works fine only when i use angularJS post it won't go thru.
why do i get OPTIONS /SubmitTicket HTTP/1.1 instead of POST?
What do i need to do to POST ? I have read about it it says something like CORS is adding OPTIONS header but why?
When you invoke the CORS requests, the browser always sends the OPTIONS request to server to know what methods are actually allowed. So this is the desired behaviour. This is so called: "Preflighted request", see: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ (section: "Preflighted requests")
Therefore in your case, you have to allow the OPTIONS method in 'Access-Control-Allow-Methods' header of your CORS filter.
My understanding is that angular initially sends an OPTIONS request to the server in order to ask the server if the full request is permissable.
The server will then respond with Headers specifying what is and is not allowed.
I guess this might be an issue with the server returning the wrong CORS headers.
You said that the server returns an error please post that error here.
See Preflighted CORS request at: http://www.staticapps.org/articles/cross-domain-requests-with-cors
and
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Should only need to do this code to get it to work:
angular.module('TestApp', [])
.factory('someService', ['$http', someService]);
function someService() {
var service = {
save: save
};
var serviceUrl = '/some/Url';
return service;
function save(data) {
$http.post(serviceUrl, data)
.success(function(data, status, headers, config) {
alert(data);
})
.error(function(data, status, headers, config) {
console.log("Error");
});
}
}
Then pull your someService into your controller and use:
someService.save(data);

Angular $http request in the controller does not work

I have the following controller. It works all fine (it parses the data and sends them into the view). The only problem I have is that it does not send $http request. Here is the code block of controller (i just send a test $http without any value from the view just to test it works or not, which does not work):
(It's also worth mentioning that I check via browser's console to see if any ajax request is sent or not)
// Controller
LoginApp.controller("RegisterController", function($scope, $http, registerService){
var username = null;
var password = null;
$scope.registerSubmit = function(){
username = $scope.register.username;
password = $scope.register.password;
};
//registerService.CheckUser();
$http.post('server.php', {name : 'something'})
.success(function(data, status, header, config){
return data;
})
.error(function(data, status, header, config){
return data;
}); // end of $http request
});
EDIT: I have edited what #JoshBeam has recommended, passing data to the post(), but it does not change anything.
You need to pass data along with the HTTP request. According to the AngularJS documentation, it is in this format: post(url, data, [config]);
Thus:
$http.post('server.php', /* your data */);

Angular $http.get with dynamic route?

I'm fairly new to angular and I'm trying to understand how to query from a REST API using a scope variable to determine the URI that is being pulled in the get request.
Lets say I'm in my app.controller and it has a service that spits out an array of numbers.. and for the sake of making the code minimal, I'll skip to the important part:
$scope.currentCompanyId = '0001';
$http.get('/api/'+ $scope.currentCompanyId +'/c').
success(function(data, status, headers, config) {
$scope.cData = data;
}).
error(function(data, status, headers, config) {
// log error
});
I know this is cheating because the $http.get is in the controller. I know it needs to be a factory of some kind.. but I have no idea how to pass the $scope.currentCompanyID to the get request and have it return the JSON. Furthermore, if $scope.currentCompanyID were to change to another number, say... '0002'.. how would the $scope.cData change to reflect the new query?
I don't think using $http in your controller is cheating - one reason for putting it into a factory/service is make it reusable. If you are only doing it in one place a service doesn't add much.
That being said, your service can return a function that takes a parameter:
app.factory("service", function($http) {
return {
getCompany: function(companyId) { ...make $http call and return data... }
}
});
then in your controller:
service.getCompany($scope.currentComanyId).then(function(resp) {...})
You should consider using Angular $resource because it handles a lot of your abstractions. Either way, if you want to make a new request based on changes in the scope variable, you can $watch it:
$scope.$watch('currentCompanyId', function() {
if(!$scope.currentCompanyId) return;
$http.get().success(); // replace with whatever mechanism you use to request data
});
Your request wont launch if currentCompanyId change... You need to lauch your request manually .
otherwise, it seem to be correct
Did you look at $resource service? http://docs.angularjs.org/api/ngResource/service/$resource - it is rather convenient way to REST requests, and docs have quite a few examples that should suit you well
About changing $scope.currentCompanyID - it seems that you need to create watch for this case:
scope.$watch('currentCompanyID', function(newValue, oldValue) {
// do your update here, assigning $scope.cData with the value returned
// using your code:
$http.get('/api/'+ $scope.currentCompanyId +'/c').
success(function(data, status, headers, config) {
$scope.cData = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
You simply need to pass the data in when calling your service. In your controller, you would need to include your service as a DI module and address it as so:
window.angular.module('myControllerModule', [])
.controller('myController', ['$scope', 'myHTTPService',
function($scope, myHTTPService){
$scope.currentCompanyId = 1;
$scope.lookupPromise = myHTTPService.get($scope.currentCompanyId);
$scope.lookupPromise.then(function(data){
//things to do when the call is successful
},function(data){
//things to do when the call fails
});
}]);
In your service, you deal with that value like this:
window.angualr.module('myHTTPServiceModule', [])
.factory('myHTTPService', '$http',
function($http){
function callHTTP(url){
return $http.get('/api/' + url + '/c');
}
return {
get: callHTTP
};
});

In Angular JS application, how do you handle the cases where there is no response from the server?

Lets say I have a route set up like so:
$routeProvider.
when('/myroute', {templateUrl: '/views/RouteA.html', controller: 'AController'}).
otherwise({redirectTo: '/home'})
If the server is down, when I click a link to "http://myapp.com/#/myroute" I can see that the requests to load the RouteA.html file are timing out. However, to the user, the application just sits there leaving them with no indication of a problem. I don't see any clear explanation anywhere for handling this type of non-response.
The Best way to tackle this is to add routeChangeError event
$rootScope.$on("$routeChangeError", function () {
alert("there is some error");
//do what ever you want to do again
});
Maybe this cant be a hint for you...
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

communication between express + angularJS

with angularJS i have got a datafile, where i communicate with the database.
Therefore i want to send the data to the i got from the frontend to send it to the packend, but somehow this is now working. can you please help me.
app.get('/api/data/:id', function (req, res) {
res.json({...});
});
app.post('/api/data/', function (req, res) {
res.json({
success: true
})
});
for the get and delete functions this works fine, but I have no idea how to make the post and put function and how to get the data in there.
Here what i do on the client
add:function (data) {
location = '/api/data/';
$http.put(location, merchant, successCb).
success(function(data, status, headers, config) {
console.log(arguments);
successCb(data);
}).
error(function(data, status, headers, config) {
console.log('Error:' + arguments);
});
},
can someone please help me how to write that on the server and client. (i get the right data on the client and its a simple javascript object.
you must use $resource which is the correct way for communicating with restful server side data source...
angularjs has very nice examples about $resource here:
http://docs.angularjs.org/api/ngResource.$resource

Categories

Resources