Angular JS POST Submission Failure - angularjs

I'm new to angular JS. I've followed an online tutorial and created a simple login form on the frontend, and linked it to the backend. Or at least I've tried. The backend is a nodejs/express server, which has a route for handling the login attempts from the frontend. It will be checking to see if the username and password used on the form are from an existing user account, or not.
The problem is that for some reason, the http POST call from the angular controller, always results in a ERR_CONNECTION_TIMED_OUT response in the browser console.
The thing is, though if I interface with the api endpoint using curl, it works just fine and the server does exactly what it's supposed to do. Just for some reason the angular frontend form cannot connect to the backend. Here's the angular controller code:
app.controller('loginCtrl, function($scope, $location, $http){
$scope.login = function(){
var parameter = JSON.stringify({ username: $scope.username, password: $scope.password });
$http({
url: 'https://localhost:8443/api/login'
method: 'POST',
data: parameter
}).then(function(response){
console.log('success: ' + JSON.stringify(response));
},
function(response){
console.log('failed: ' + JSON.stringify(response));
});
}
});
The nodejs backend server is serving content over HTTPS. This controller function (login) is being hit, and the POST is being made, but it simply times out. And again, manually interfacing with these api endpoints works as expected when using curl or wget.
Any insight into the issue or what I'm doing wrong?

Related

Can not get response cookie from angular $http post using ionic

I am sending a post auth request from my localhost to a remote server to get response cookies returned by server(using ionic proxy to solve CORS). From chrome network inspector, I can see the response cookie has been returned from server. However, I am not able to access it from $http post response. I try almost everything from other posts and I still can not get the cookie. What I have tried
I use ngCookie and $timeout combination. Basically I get an empty object when I use $cookie.getAll() which I assume the cookie is not there
I also set withCredentials to true
I also tried headers.get('set-cookie')
My angular version is 1.5.3. Please help
Below is my code
angular.module('starter.controllers', ['ngCookies'])
.controller('DashCtrl', function($scope, $http, $cookies, $timeout) {
$http({
method: 'POST',
url: '/api/User/Authenticate',
data: {
Username: 'xxx',
Password: 'xxx'
},
withCredentials: true
}).then(function(response) {
$timeout(function() {
console.log($cookies); // return {}
console.log($cookies.getAll()); // return {}
});
}, function(response) {
});
})
Here is the server response

AngularJS $resource GET params appear in URL

My REST backend [ based on NodeJS/express/mongojs] is complaining 404 (not found) when Params are attached as part of URL. Backend rest interface is coded as below;
var express = require('express');
var router = express.Router();
router.get('/login', auth.signin); //auth.signin is code to verify user
Above REST service is consumed by AngularJS based frontend through $resource as below;
Definition:
angular.module('myapp').factory('signinmgr', function($resource) {
return $resource("http://localhost:3000/login", {}, {
'get': {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}});
Usage:
signinmgr.get({'username':'myname', 'password':'mypass'}, function(data){
//success
}, function(x){
//failed
});
Problem:
Frontend code above produces a URL to consume REST service where parameters are part of URL i.e. http://localhost:port/login?username=myname&password=mypass [if I use GET method, POST is OK]. I wanted my front end to keep URL as http://localhost:port/login and post any parameters through body as backend is using req.body.paramName to read those. [Actual Solution]
If (1) cannot be done, and my frontend is sending params as part of URL, I needed help as to know how to equip my backend to allow this URL with parameters so that backend doesnt return 404 as the base URL http://localhost:port/login is already there.
PS: for (1), I tried this thread with data:{username:'',password:''} but of no use. Please help if I am missing something very obvious or some concept.
Try the $http service instead:
angular.module('myapp').factor('signinmgr', function($http) {
return {
login: function (username, password) {
$http.post("http://localhost:3000/login", {
username: username,
password: password
}
}
};
});
signinmgr.login('myname', 'mypass').then(function(data){
//success
}, function(x){
//failed
});
Each request that my nodejs/expressjs backend receives has three places for passed attributes;
params{}
query{}
body{}
My problem (1) cannot be fixed in case I want to use GET method since with GET request parameters are visible as part of URL i.e. http://localhost:port/login?username=myname&password=mypass. To send my username/password I had to use POST that sends parameters as part of body{}.
My problem (2) was that I was using GET and mistakenly looking for parameters in body{} of request. Instead, parameters passed as part of URL in GET request are added to query{} of the request.

Implementation of REST web service using Slim framework on an ionic application to signin

I'm a beginner in the use of the ionic framework , and I'm trying to implement a login and user authentication system using a RESTful web service developed on the Slim framework. In fact, my client side is almost ready and my REST web service using the Slim framework also is ready and I tested that it works.
What I need to know is how to implement this last part with my application (client side). I will need the http service of AngularJS but i don't understand how to do it.
Please, can you help me with examples or links?
(function(){
angular.module('app')
.controller('AppController', ['$scope', '$http', function($scope, $http){
$scope.data = "";
$scope.getData = function(){
$http.get('urlToYourMethod')
.success(function(data){
$scope.data = data;
})
.error(function(er){
});
};
$scope.getData();
}]);
})();
Edit
if you want to pass header parameters, the easiest way to do this is as follow:
var req =
{
method : 'POST',
url : 'your url',
headers: {
'Accept' : 'application/json',
'Content-Type': 'text/plain; charset=utf-8'
},
data : output
};
Note :
-- headers depends on what you are sending and receiving.... There are info on headers here:
https://docs.angularjs.org/api/ng/service/$http
-- dataParameter needs to be "data" : "test" (not "myData" : "test")
-- If GET request, delete data parameter

Access Control Allow Origin | AngularJS

I was integrating the flickr app into my app.
I am receiving the error below:
XMLHttpRequest cannot load https://api/flickr.com/services/rest?api_key=4cd95b5ad05844319ee958bf96ec0150&format=json&method=flickr.photos.search&nojsoncallback=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sinch12j12.ads.autodesk.com' is therefore not allowed access. The response had HTTP status code 400.
Below is the client side code:
(function() {
'use strict';
angular.module('flickrApp', ['ngMaterial'])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])
.controller('ListController', ['$scope', '$http', function($scope, $http) {
$scope.results = [];
$scope.search = function() {
$http({
method: 'GET',
url: 'https://api/flickr.com/services/rest',
params: {
method: 'flickr.photos.search',
api_key: '4cd95b5ad05844319ee958bf96ec0150',
text: $scope.searchTerm,
format: 'json',
nojsoncallback: 1
}
}).success(function(data) {
$scope.results = data;
}).error(function(error) {
console.log(error);
});
}
}]);
})();
Please let me know how shall it may be resolved ?
You are trying to make AJAX requests to a different server (domain), that does not allow ajax requests from other domains. There are 2 solutions to your problem :
Edit the configurations of the remote server (Allow-Origin header) to allow AJAX requests from other servers. I think this solutions is not feasible in your case, as you are not capable of configuring the flickr server
Create a proxy server component in your server, exposing an API to your application. Thus, you will make the AJAX requests to your API (and since it is the same domain, you will not have a cross-domain request issue), and your server will make the requests to the flickr API and respond in your AJAX call.
You're trying to use AJAX to retrieve some data from a remote server (in this case, the Flickr server). For security reasons, AJAX calls to any file on a remote server is not permitted unless that file has allowed AJAX calls from remote servers. Here, the Flickr file your trying to get doesn't allow AJAX calls from any other servers, that's why you won't be able to access the data in that file.
Thanks and let me know if you have any more problems.

Web API loads via URL but get Error 404 from Angular script

I have a WebAPI method here:
http://localhost:50463/api/movies
and when accessing it from a browser it loads perfectly.
In my project (the same project as where Web API resides) when calling the method from AngularJS I get an error 500:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
When I click the link in the error it loads the data perfectly.
The routing for WebAPI is as follows:
config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}",
new {action = "Get"},
new {httpMethod = new HttpMethodConstraint(HttpMethod.Get)}
);
This is the angular call
app.factory('dataFactory', function ($http) {
var factory = {};
factory.data = function (callback) {
$http.get('/api/movies').success(callback);
};
return factory;
});
I added this javascript just to rule-out angular, I get the same:
$.ajax({
url: "/api/movies",
type: 'GET',
//data: "{ 'ID': " + id + "}",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
Any idea what I have done wrong?
I assume your Web API and AngularJS app are running on a different port. In this case you are running in a Same-Origin-Policy issue.
Ensure your Web API is responding with HTTP CORS headers e.g.:
Access-Control-Allow-Origin: http://<angular_domain>:<angular_port>
or
Access-Control-Allow-Origin: *
Doesn't look like a CORS issue to me as you are using a relative URL in your $.ajax() request.
Did you try $.getJSON("/api/movies").then(successHandler, faulureHandler)
Not sure of that will help but for one you are sending a contentType header with a GET request which contains no content. There should be an Accept header instead, but WebAPI should be fine without one.
I would also remove the constrains from the routing and revert back to the default route mapping to see if the problem is there.
config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional});

Resources