communication between express + angularJS - javascript

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

Related

using angular $http.post will not post to file

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.

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

Unable to get authenticated using Redmine REST API

I am building a mobile application for Redmine. So, to get data from the Redmine server, I need to authenticate the user by passing his password and username. In Redmine API documentation, two methods are mentioned for authentication.
using your regular login/password via HTTP Basic authentication.
using your API key which is a handy way to avoid putting a password
in a script. The API key may be attached to each request in one of
the following way:
- passed in as a "key" parameter
- passed in as a username with a random password via HTTP Basic
authentication
- passed in as a "X-Redmine-API-Key" HTTP header (added in Redmine
1.1.0)
I tried to send a get request as follows, I can see the issue list in response to the Get request in browser. But the success callback is not triggering.
var url= "http://username:password#redmine.qburst.com/issues.json";
$http({
method: 'JSONP',
url: url
}).
success(function(data, status) {
console.log(data);
}).
error(function(data, status) {
console.log("Error "+status);
});
The following error is coming in console.
SyntaxError: missing ; before statement
{"issues":[{"id":139989,"project":{"id":215,"name":"Book Meeting Room
Error status is 0.
Different to standard JSON, JSONP responses should be wrapped in a function call.
Instead of:
{"issues":[{"id":139989,"project":{"id":215,"name":"Book Meeting Room...
You should be getting something like the following from the server:
handler({"issues":[{"id":139989,"project":{"id":215,"name":"Book Meeting Room"}}]});
I ran into a similar issue and found that passing the callback or jsonp parameter with a handler name solved it. More info here in the redmine documentation.
In jQuery this would be my request:
$.get('someurl', {'callback': 'foo'}, function (data, status, xhr) {
... request logic ...
}, 'jsonp'
);
...and this would be your request with the callback parameter:
$http({
method: 'JSONP',
url: url,
callback: 'something'
}).
success(function(data, status) {
console.log(data);
}).
error(function(data, status) {
console.log("Error "+status);
});
This may not help you with the authentication woes but will hopefully get you past this error.

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

Handle an express redirect from Angular POST

I'm using Expressjs as an API and I'm using angular to hit that POST. I would like to respond to the redirect that express is sending. Success from my Angular POST returns a HTML of the page I intend to redirect to but nothing happens on my DOM. I can see that my redirect is working in my network traffic, and that console.log data, below contains the DOM of the redirected page.
How can I refresh the DOM, to reflect this successful POST, or handle the "redirect"?
ANGULAR CODE:
$http({method: 'POST', url: '/login', data:FormData}).
success(function(data, status, headers, config) {
console.log(data)
}).
error(function(data, status, headers, config) {
});
$scope.userName = '';
Expressjs API:
app.post('/login', function(req, res){
var name = req.param('name', null); // second parameter is default
var password = req.param('password', "changeme")
// Lots Authenticationcode
// returns succesfful login
res.redirect('http://localhost:3000/');
}); // end app.post
console.log(data) (from Angular POST success)
returns the HTML of the page I intended to redirect to
AngularJS is meant to work as a client-side framework coupled with (mostly) RESTfull APIs. Your login API isn't supposed to return a HTML, it is supposed to return the instruction to redirect. So in your case you should simply call $location.url('/') in your $http success callback, which would use the Angular router to "redirect" to '/' (the root URL).

Categories

Resources