$http.get success method not called - angularjs

I am new to AngularJS & NodeJS. I am trying to get a API response from NodeJS and display it in angular. I am using $http to make API call. Below is my nodeJS code.
var express = require('express');
var app = express();
app.get('/employees',function(req,res)
{
console.log("Test Output :");
res.status(200).send('Hello User');
});
app.listen(8080);
Below is my angular code
var myapp = angular.module('myapp',[]).controller('myappController', ['$scope','$http',function ($scope,$http){
$http.get('http://127.0.0.1:8080/employees')
.then(function(response)
{
window.alert("Success");
$scope.emdata=response.data;
},function(errorresponse)
{
window.alert("Error");
$scope.emdata=errorresponse.status;
});
}]);
I am using expression {{emdata}} in HTML page. When I open the HTML page I can see the console output "Test Output " in NodeJS terminal which means the API is getting called but I dont see "Hello User" in HTML page. It looks like the success function in $http.get is not getting called and only the error function is getting called. So I see an alert window with "Error" whenever I open the HTML page and response status as -1 in the place of {{emdata}}.
When I tried making the API call using Postman I get correct response with status 200. So I am wondering what is wrong?

Check headers, i.e. what format is accepted by $http request and the format of the response (JSON, plain text, etc).
Fix value in
$httpProvider.defaults.headers.common
or set needed one in
$httpProvider.defaults.headers.get = { ... };
or just use
var requestParams = {
method: 'GET',
url: '...',
headers: {
...
}
};
$http(requestParams).then(...);
Take a look at Setting HTTP Headers in official manual for more details.

Related

Passing External API to Angularjs

I'm working with an external API from Shipstation. I can do a GET request to pull the information in just fine into Nodejs, but I can't figure out how I can transfer that data client-side to manipulate within Angular? I've been struggling with this for a few days now and all my googling searching isn't helping out.
server.js
var express = require('express');
var request = require('request');
var app = express();
app.use(express.static('public'));
var Orders = require('./controllers/ordersController');
app.use('/orders', Orders);
app.listen(3000, function() {
console.log('I am live on port 3000');
});
ordersController.js
var request = require('request');
module.export = request({
method: 'GET',
url: 'https://ssapi.shipstation.com/orders/listbytag?orderStatus=awaiting_shipment&tagId=32099&page=1&pageSize=100',
headers: {
'Authorization': 'xxxxxxxxxxx'
}}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
});
I figured the best way was to put the GET request in its own "orders" module, export it, and then have angular access that route in an http request (/orders). Sounds good in theory, right?
I appreciate the help in advance! Thanks guys!
I'm assuming that the ShipStation API provides JSON which is easily consumable by Angular.
You can load the JSON into your Angular app like this:
$http.get('/orders:3000', function(data) {
$scope.Orders = data;
console.log($scope.Orders);
});
Add this to your controller, then check the browser's developer console to see the output. From there, you can manipulate the JSON object however you need and display the information in your HTML view.

How to get,multiple GET request params from angular to nodejs/Express js

I want to retrieve various request params in express sent to me by angular but I keep on getting 404 error:
Code angular controller:
var config = {
params: { userid: "userffvfid ",
pass:"abcd"
}};
$http.get('/erai',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response; });
Node js/Express js code:
app.get('/erai',function(req,res){
console.log("got request");
console.log(req.params.userid);
console.log(req.params.pass);
res.send("hello");
});
How do i access the params properly and respond to it properly w/o getting 404 error?
When making a get request like that any payload will be appended in the url.
So the final request url will be something like
http://www.example.com?user=John&password=Doe
To access those variables in express use the req.query object
in your case
var userid = req.query.userid
var pass = req.query.pass
If you go the POST way your data will be in the payload
You will have to use a body parser middleware and then access the data with
req.body

Getting 401 error when call $http POST and passing data

I am calling a Web API 2 backend from an angularjs client. The backend is using windows authentication and I have set up the $httpProvider to use credentials with all calls and it works fine for all GETS.
Like this:
$httpProvider.defaults.withCredentials = true
But, when using the POST verb method AND passing a data js object I get a 401 error. If I remove the data object from the $http.post call it reaches the endpoint but I would like to pass up the data I need to save.
Here's an example of the client-side call:
var saveIndicator = function (indicator) {
var req = {
method: 'POST',
url: baseUrl + "/api/indicators",
data: indicator
};
return $http(req).then(function (response) {
return response.data;
});
};

angular js post request to nodejs json. key undefined express 4

https://codeforgeek.com/2014/07/angular-post-request-php/
Hi I was following the above link to give post request from angular js to node js. I received the data posted in below format when i give
console.log(req.body);
{ '{"email":"test#test.com","pass":"password"}': '' }
and when i try to get the value as below, it says undefined.
var email = req.body.email;
console.log(email);
I am unable to get the value of email and pass. Thank you
change the client side header code to headers: { 'Content-Type': 'application/json' }
Your Angular code is sending JSON data, but your Express app is parsing it as URL encoded data.
You probably have something like this in your Express app:
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded());
That last line should be:
app.use(bodyParser.json());
You did not well explain the problem , please next time try to post a bigger part of your code so we could understand what you wanted to do / to say .
To answer your question i will copy/paste a part of my code that enable you to receive a post request from your frontend application(angularJS) to your backend application (NodeJS), and another function that enable you to do the inverse send a post request from nodeJS to another application (that might consume it):
1) receive a request send from angularJS or whatever inside your nodeJS app
//Import the necessary libraries/declare the necessary objects
var express = require("express");
var myParser = require("body-parser");
var app = express();
// we will need the following imports for the inverse operation
var https = require('https')
var querystring = require('querystring')
// we need these variables for the post request:
var Vorname ;
var Name ;
var e_mail ;
var Strasse ;
app.use(myParser.urlencoded({extended : true}));
// the post request is send from http://localhost:8080/yourpath
app.post("/yourpath", function(request, response ) {
// test the post request
if (!request.body) return res.sendStatus(400);
// fill the variables with the user data
Vorname =request.body.Vorname;
Name =request.body.Name;
e_mail =request.body.e_mail;
Strasse =request.body.Strasse;
response.status(200).send(request.body.title);
});
2) Do the inverse send a POST request from a nodeJS application to another application
function sendPostRequest()
{
// prepare the data that we are going to send to anymotion
var jsonData = querystring.stringify({
"Land": "Land",
"Vorname": "Vorname",
"Name": "Name",
"Strasse": Strasse,
});
var post_options = {
host: 'achref.gassoumi.de',
port: '443',
method: 'POST',
path: '/api/mAPI',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': jsonData.length
}
};
// request object
var post_req = https.request(post_options, function(res) {
var result = '';
res.on('data', function (chunk) {
result += chunk;
console.log(result);
});
res.on('end', function () {
// show the result in the console : the thrown result in response of our post request
console.log(result);
});
res.on('error', function (err) {
// show possible error while receiving the result of our post request
console.log(err);
})
});
post_req.on('error', function (err) {
// show error if the post request is not succeed
console.log(err);
});
// post the data
post_req.write(jsonData);
post_req.end();
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
}
So finally , I hope this answer will helps anyone who is looking on how to get a post request in node JS and how to send a Post request from nodeJS application.
For further details about how to receive a post request please read the npm documentation for body-parser library : npm official website documentation
I hope you enjoyed this and Viel spaß(have fun in german language).

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