I'm new to node and angular script. I'm having a function readDetails within my service which gives a GET request.
this.readDetails = function() {
return $http({
method: 'GET',
url: '/getDetails'
}).then(function(data) {
return data;
});
}
Given below is my server side code.
app.get('/getDetails', function(request, response) {
fs.readFile('details.json', 'utf8', function(err, data) {
if (err) throw err;
var obj = JSON.parse(data);
response.send(obj);
response.end();
})
})
I don't get the response from the server. I do not find Why. Suggestions are welcome
Related
I need to create service in AngularJS to return the response of HTTP requests. My problem is the asynchronous request, because after I've submitted the request, my function returns undefined instantly and does not return the response from the server.
app.service('TesteService', function($http) {
this.teste = function(data) {
var data = "*";
$http({
method: 'GET',
url: 'teste-s.php',
params: {data: "bem recebido"}
}).then(function successCallback(response) {
data = response.data;
alert(data);
return data;
}, function errorCallback(response) {
data = "500";
});
}
});
How do I fix this?
I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed
I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});
All:
[UPDATE] I figure it out, it turns out that:
$http({
url: "http://localhost:3000/users",
method: "JSONP",
params: {
callback:"JSON_CALLBACK", // need to be this name
q: $scope.qs
}
})
.success(function( data ){
console.log("return data length:",data.length);
if(data.length>0){
$scope.cdata = data;
}
})
==========================================================
I am new to ExpressJS and AngularJS, right now, I m trying to use Express to build a REST JSONP service to provide data.
And when I try Angular in the frontend like:
$scope.qs = 0;
$http({
url: "http://localhost:3000/users",
method: "JSONP",
params: {
callback:"dataservice",
q: $scope.qs
}
})
.success(function(err, data){
console.log("return data length:",data.length);
if(data.length>0){
$scope.cdata = data;
}
})
.error(function(data, err){
console.log(data, err);
});
};
Annd on server side I use:
/* GET users listing. */
router.get('/', function(req, res) {
var jsonp = req.query.callback;
var start = parseInt(req.query.q);
var retdata = [];
if( !isNaN(start) ){
retdata = cdata.slice(start);
}
if(jsonp){
console.log("I return as JSONP");
res.jsonp( retdata );
}else {
console.log("I return as JSON");
res.json( retdata );
}
});
From chrome console, I can see the return JSONP response is like:
/**/ typeof dataservice === 'function' && dataservice([{"Name":"Island Trading","City":"Cowes","Country":"UK"},{"Name":"Königlich Essen","City":"Brandenburg","Country":"Germany"},{"Name":"Laughing Bacchus Wine Cellars","City":"Vancouver","Country":"Canada"},{"Name":"Magazzini Alimentari Riuniti","City":"Bergamo","Country":"Italy"},{"Name":"North/South","City":"London","Country":"UK"},{"Name":"Paris spécialités","City":"Paris","Country":"France"},{"Name":"Rattlesnake Canyon Grocery","City":"Albuquerque","Country":"USA"},{"Name":"Simons bistro","City":"København","Country":"Denmark"},{"Name":"The Big Cheese","City":"Portland","Country":"USA"},{"Name":"Vaffeljernet","City":"Århus","Country":"Denmark"},{"Name":"Wolski Zajazd","City":"Warszawa","Country":"Poland"}]);
But Angular can not use it in .successs, but trigger the .error handler.
I wonder if anyone can help me with this? How to use the return response
Thanks
Try this instead, you are sending the callback so that is what you have to call to retrieve the data:
function userCallback(data) {
console.log("return data length:",data.length);
if(data.length>0){
$scope.cdata = data;
}
}
$http({
url: "http://localhost:3000/users",
method: "JSONP",
params: {
callback: userCallback,
q: $scope.qs
}
}).then(userCallback);
Here how my button's set up. The Updates.getUpdates is working. Updates.postAnUpdate returns 404
$scope.postUpdate = function () {
console.log($scope.update);
Updates.postAnUpdate($scope.update);
Updates.getUpdates().then(function (data) {
$scope.updates = data;
});
};
Here is my lovely services
app.factory('Updates', ['$http',
function ($http) {
return {
//Get the current users messages
getUpdates: function () {
return $http({
url: '/updates/',
method: 'get'
}).then(function (result) {
return result.data;
});
},
postAnUpdate: function (update) {
return $http({
url: '/updates/post',
method: 'post',
data: {
update:update,
}
}).then(function (result) {
return result.data;
});
}
};
}]);
Here's my routes to handle the urls
var updates = require('./routes/updates.js');
//Project Updates
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
And finally, here's the code that works with a 200 and console text.
exports.getAll = function (req, res) {
console.log('It worked');
}
So everything should be working for the post too, but it isn't. I'm just trying to do a console command so I know it works and I'm getting a 404
exports.newPost = function (req, res) {
var db = mongo.db,
BSON = mongo.BSON,
newPost = {};
console.log('This is giving me 404 instead of showing up in terminal');
newPost.content = req.body.update;
newPost.author = req.user._id;
newPost.date = new Date();
db.collection('updates').save(newPost, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
}
Looks as though this is a simple typographic error. in your routes:
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
I think you want
app.post('/updates/post', updates.newPost);