angular promise response.data is empty - angularjs

factory:
angular.module('clientApp').factory('Di', function($http) {
return {
create: function(dis){
return $http.post('/dis', dis);
}
});
Controller:
'use strict';
angular.module('clientApp').controller('AdminCtrl', function($scope, toastr, Di) {
$scope.di = {};
$scope.dis = [];
$scope.add = function(){
Di.create($scope.di).then(function(response){
console.log(response, 'front data post')
$scope.dis.push(response.data);
$scope.di= {};
});
};
});
When I console.log() the response, the only thing I see in response.data is the hashKey. I do see the object in response.config.data, but from what I've seen online, this is just the original object i'm sending to the database, not the returned promise, right?
The data is saving to the database.
What am I doing wrong? I've done a similar configuration successfully with other promises, but the response is not what I'm expecting here.
API
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DiSchema = new mongoose.Schema({
name: { type: String, lowercase: true , required: true },
photo: { type: String },
email: { type: String, unique: true, lowercase: true },
year: { type: Number},
timestamp: { type : Date, default: Date.now },
description: { type: String},
location: { type: Array },
social: {
website: {type: String},
facebook: {type: String },
twitter: {type: String },
instagram: {type: String }
}
});
DiSchema.methods.create = function(o, cb){
this.model.save(o, cb);
};
module.exports = mongoose.model('Di', DiSchema);
controller:
'use strict';
var Di = require('../models/di');
exports.create = function(req, res){
Di.create(req.body , user, function(err, di){
console.log('req.body.di', req.body);
res.send({di:di});
});
};
Routes:
var dis = require('../contollers/dis');
app.post('/dis', dis.create);

You had a typo with an extra parameter within your create function.
exports.create = function(req, res){
Di.create(req.body , function(err, di){
console.log('req.body.di', req.body);
res.send({di:di});
});
};

I think you should bind your promise to the scope.
Would that fix the problem? Can you try?
$scope.add = function(){
Di.create($scope.di).then(function(response){
console.log(response, 'front data post')
$scope.dis.push(response.data);
$scope.di= {};
}.bind($scope));
};

Related

how can i add array of objects in schemaless mongoose?

**model schema**
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var item = new Schema({
name:{type: String,
required: true},
price:{type: String}
})
var object=new Schema({
name:{type: String,
required: true},
items: [item]
});
api.js, posting data to server
router.post('/objectss', function(req, res){
var object= new Object(); **
how can i save array of objects in array
**
object.items.push({firstName: req.body.fname, lastName: req.body.lname});
object.name = req.body.name;
object.save(function (err) {
if(err) throw err;
res.json({success: true, message:'allahuakbar'});
});
// saved!
});
angularjs controller
$scope.addProduct = function(){
$scope.items.push({
fname: $scope.item.fname,
lname: $scope.item.lname
});
$scope.item = {};
}
$scope.submitx = function(inv, item){
console.log(inv);
var object = {
name:inv.name,
fname:items.fname,
totalValue: 0
}
PostBlog.createInvoice(objects).then(function(data){
console.log(data);
});
$scope.objects= {};
}
please see this code and help me! struggling over weeks . there is array of object like a["name":carrot, "price":24, "":, etc]
those who get stuck refer to this instead of using method
router.post('/invoices', function(req, res){ //by making route in from
var invoice = new Invoice();
for (var i = 0; i < req.body.length; i++) {
invoice.items.push({name:req.body.fname[i].fname});
}
invoice.name = req.body.name;
//invoice.items.insertMany(items, function(error, next) {
invoice.save(function (err) {
if(err) throw err;
res.json({success: true, message:'allahuakbar'});
});
// saved!
});

Saving upvote value to database (MEAN stack - reddit clone)

I have been working on a reddit clone from the thinkster.io tutorial, and I can not figure out how to save upvote values to the database. Could some one please take a look?
// from angularApp.js
.factory('posts', ['$http', 'auth', function($http, auth){
var o = {
posts: []
};
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
post.votes += 1;
});
};
return o;
}])
.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
$scope.posts = posts.posts;
$scope.isLoggedIn = auth.isLoggedIn;
$scope.addPost = function(){
//prevents empty posts
if(($scope.title === '') || ($scope.body === '')) { return; }
//creates post
posts.create({
title: $scope.title,
votes: 0,
createdOn: Date.now(),
link: $scope.link,
body: $scope.body,
});
//returns empty values after post is created
$scope.title = '';
$scope.link = '';
$scope.body = '';
};
$scope.incrementUpvotes = function(post){
posts.upvote(post);
};
}])
//mongoose post schema
var PostSchema = new mongoose.Schema({
title: { type: String, required: '{PATH} is required!'},
body: String,
createdOn: { type: Date, default: Date.now },
votes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
author: String
});
PostSchema.methods.upvote = function(cb) {
this.votes += 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
// from index.js
// upvote a post
router.put('/posts/:post/upvote', auth, function(req, res, next) {
req.post.upvote(function(err, comment){
if (err) { return next(err); }
res.json(comment);
});
});
//from index.ejs (html)
<i ng-click="incrementUpvotes(post)" class="ion-chevron-up"></i><br>
{{comment.votes}}<br>
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', null, { ...

how to post http req with multiple param in angularjs,mongoose

In the view html page there is a form with a table and when i submit the form two objects are created cvm and schedules for form and table. i somehow want schedules(which is an array) to be related to cvm form. so i tried this way...
Here is the defined model
$scope.addSchedule=function(schedule)
{
console.log(schedule.startDate);
console.log(schedule.location);
$scope.schedules.push({
startDate: schedule.startDate,
location: schedule.location
});
schedule.startDate='';
schedule.location='';
};
var inData={'cvm': $scope.cvm,'schedules': $scope.schedules};
$scope.addCvm=function()
{
console.log($scope.cvm);
console.log($scope.schedules);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
sever side Connection
i guess somthing i missed in this part
/* POST */
router.post('/', function(req, res, next)
{
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
Here is my schema for mongodb
'use strict';
var mongoose = require('mongoose');
var cvmSchema = new mongoose.Schema({
visitOrganization: { type: String },
visitAgenda: { type: String },
accountManager: { type: String },
visitCoordinator: { type: String },
schedules:[{
startDate: String,
location: String
}]
});
module.exports = mongoose.model('visit', cvmSchema);
plz help !! thanks in advance
I think you should try with below change :
//Change addCvm function
$scope.addCvm = function(){
var inData = $scope.cvm;
inData.schedules = $scope.schedules;
console.log(inData);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
// Server Side API Code
router.post('/cvmApi', function(req, res, next) {
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
The thing is i dint realize my variable startDate was not in type string in my html page as i was using some date plugins....
soo ya thats it worked brilliantly ...
addCvm function in controller thanks to rana ;-)
$scope.schedules=[];
$scope.addCvm = function(){
var inData = $scope.cvm;
inData.schedules = $scope.schedules;
console.log(inData);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
server side Api
router.post('/', function(req, res, next) {
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
may be not required but i changed my schema though....
var cvmSchema = new mongoose.Schema({
visitOrganization: { type: String },
visitAgenda: { type: String },
accountManager: { type: String },
visitCoordinator: { type: String },
schedules: [{
dateStart: { type:String },
locationHere: { type: String }
}]
});

Mongodb CRUD operation with Angularjs and nodejs - How to get message from database if data is already exist?

In controller.js:
angular.module('CRUD').controller('myController',['$scope','$http', function($scope,$http){
$scope.sendData = function(){
console.log($scope.data1);
var formData = {
"username" :$scope.username,
"email" :$scope.email
};
$http({
url:'/formData',
method:'POST',
data:formData
}).success(function(data){
console.log(data);
});
}
}]).directive("myFirstDirective",function(){
return
{
template:"<b>custom directive</b>",
restrict:'E';
}
});
In your nodeJS route API
//User Schema
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
email: {
type: String,
unique: true //means the email has to be unique across all documents
}
});
UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
module.exports = mongoose.model('User', UserSchema);
...
//API
app.post('/formData', function(req, res){
User.create(req.body, function(err){
if (!err){
res.send(200); //user created
}
else {
if (err.name === 'ValidationError') res.send(409); //stands for form validation error
else res.send(500);
}
});
});
Good practice to put your requests in the service. For example
angular.module('CRUD').controller('myController',['$scope','$http', 'CRUDService', function($scope,$http, CRUDService){
$scope.sendData = function(){
CRUDService.createUser({
username: $scope.username,
email: $scope.email
}).then(function(res){
//all good user was created
}, function(err){
//error, failed to create user
if (err.status === 409){
//email already exists
}
});
}
}]).service('CRUDService', ['$http', function($http){
this.createUser = function(postData){
return $http.post('/formData', postData);
}
}]);

req.body undefined and express api testing using angular

I am practicing API and having a small issue. Can someone please have a look the code below and let me know why req.body logs undefined when I do POST request using angular $http on the client side? also try a simple jquery AJAX request to have the same result.
//------------------ back-end
var express = require('express');
var mongoose = require('mongoose');
var app = express();
//connect DB
var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/Ecomm_db';
mongoose.connect(mongoURI);
//express config
app.use(express.static(__dirname + '/public'));
//DB setup
var Schema = mongoose.Schema;
var Product = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
style: { type: String, unique: true },
modified: { type: Date, default: Date.now }
});
var ProductModel = mongoose.model('Product', Product);
//API
app.post('/api/products', function (req, res){
var product;
console.log("POST: ");
console.log(req.body);
product = new ProductModel({
title: req.body.title,
description: req.body.description,
style: req.body.style,
});
product.save(function (err) {
if (!err) {
return console.log("created");
} else {
return console.log(err);
}
});
return res.send(product);
});
//--------------------------- client-end
$http({
method: 'POST',
url: '/api/products',
data: {
title: "my t-shirts",
description: "super good",
style: "my style"
}
}).then(function (response){
console.log('POST response',response);
}, function (err){
console.log('err:', err);
})
Try to use module 'body-parser'
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Resources