res.send() not working in node - angularjs

I am using promise and sending the response but with in the .then() function I can't send the response using res.send();
My code is
var express = require ('express'); //EXPRESS Package
var bodyParser = require('body-parser');// get body-parser
var route = express.Router(); //define our app using express
var multer = require('multer');
var validator = require('validator');
var userModel = require('../../model/user.model');
var session = require('express-session');
route.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
route.use(bodyParser.json()); // for parsing application/json
// route.use(bodyParser.json({ type: 'application/vnd.api+json' }))
route.put("/personal/:id", function (req, res) {
data = {};
data['personal_details'] = req.body;
return userModel.update(req.params.id, data).then( function (result) {
// console.lssog(result);
res.send();
}).catch( function ( err ){
res.send(err).status(400);
});
});
// route.put("/contact/:id", function (req, res) {
// userModel.update(req.params.id, "contact_details", req.body).then( function () {
// res.sendStatus(200)
// }).catch( function ( err ){
// res.send(err).status(400);
// });
// });
module.exports = route;
Users Model file is user.model.js which is shown below:
var passwordHash = require('password-hash');
var mongo = require('mongoskin');
var Q = require('q');
var _ = require('lodash');
var randomstring = require('randomstring');
var db = mongo.db('mongodb://127.0.0.1/angulardemo');
db.bind('demotest');
// var hash = bcrypt.hashSync("12345", salt);
var model = {};
model.login = login;
model.create = create;
model.update = update;
model.destroy = destroy;
model.edit = edit;
module.exports = model;
/**
* Create new user
* #param {request data} userData
*/
function create (userData){
var deferred = Q.defer();
db.demotest.findOne({"email" : userData.email}, function (err, user) {
if (err) deferred.reject(err);
if(user){
deferred.reject('Email "' + userData.email + '" is already taken');
}
else{
createUser();
}
});
function createUser() {
var user = _.omit(userData, ['password', 'c_password']);
var hashedPassword = passwordHash.generate(userData.password);
user.password = hashedPassword;
user.api_token = randomstring.generate(50);
user.registration_code = randomstring.generate(10);
user.is_active = 1;
user.is_verified = 1;
db.demotest.insert(user, function (err, doc) {
if (err) deferred.reject(err);
deferred.resolve();
});
}
return deferred.promise;
}
/**
* Login user
* #param {user request data} data
*/
function login(data) {
var deferred = Q.defer();
db.demotest.findOne({"email" : data.email}, function (err, user) {
if (err) deferred.reject(err);
if(!user) deferred.reject("User not found");
if(user && passwordHash.verify(data.password, user.password)){
deferred.resolve(user);
}
else{
deferred.reject("Invalid Credential");
}
});
return deferred.promise;
}
/**
* Update User
* #param {user id} id
* #param {user data} data
*/
function update(id, data){
var deferred = Q.defer();
// validation
db.demotest.findById(id, function (err, user) {
if (err) deferred.reject(err);
if (user.id !== id) {
// username has changed so check if the new username is already taken
db.demotest.findOne(
{ _id: id },
function (err, user) {
if (err) deferred.reject(err);
if (user) {
// username already exists
deferred.reject('User "' + user.username + '" is already taken')
} else {
updateUser();
}
});
} else {
updateUser();
}
});
function updateUser() {
db.demotest.update(
{ _id: mongo.helper.toObjectID(id) },
{ $set: data },
function (err, doc) {
if (err) deferred.reject(err);
deferred.reject("err");
});
}
return deferred.promise;
// var deferred = Q.defer();
// db.demotest.update({_id : mongo.helper.toObjectID(id)}, {$set: data}, function (err, result) {
// console.log(result);
// if (err) deferred.reject(err);
// deferred.resolve("OLLLL");
// });
// return deferred.promise;
}
function destroy() {
}
function edit() {
}
// var insertTestDoc = function (db, callback) {
// //console.log("one"); return ;
// var collection = db.collection('demotest');
// collection.insertOne({"title" : "demotest", "description" : "Lorem Ipsum Sit Emet.", "password" : hash}, function ( err, db ){
// assert.equal(err, null);
// callback();
// });
// }
// var login = function (db, callback) {
// var collection = db.collection('demotest')
// var cursor = collection.findOne({"title" : "demotest"});
// console.log(cursor);
// // cursor.each(function(err, doc) {
// // assert.equal(err, null);
// // if (doc != null) {
// // console.log(doc);
// // } else {
// // callback();
// // }
// // });
// }
// MongoClient.connect('mongodb://localhost/angulardemo', function ( err, db ){
// assert.equal( null, err );
// console.log("Connected to the server correctly");
// login(db, function () {
// db.close();
// });
// // insertTestDoc(db, function () {
// // db.close();
// // });
// });
Please assist thanks

I can think of two possibilities based on what you've shown, one of which depends on the version of mongoose you're using. Actually, the use of mongoose is an assumption on my part, since you never mention it...
The more likely one is that you're never actually connecting to the database. In your code, somewhere, there needs to be a call to mongoose.connect() or mongoose.createConnection() that fires on app startup (or at least before the request hangs that you're seeing).
If you are in fact doing that and just didn't share it, then the next most likely thing is that you're using a version of mongoose before 4.0, in which queries (e.g. .update()) didn't follow the Promise api, and you had call exec() like:
myModel.findOneAndUpdate(req.params.id, data).exec().then(...);
If I'm wrong in my assumption about mongoose, or if both my suggestions are wrong please update your question with the relevant info.

Related

Can't figure out where to set {responseType: 'arraybuffer'}

I have been trying to set the responseType to 'arrayBuffer' in the following code, but I keep getting Failed to load pdf document
var resource = ApiService.getResource('/cases/report');
resource.get({caseId: self.CaseID,responseType:'arraybuffer'},function(data){
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
I have tried putting {responseType: 'arraybuffer'} in the getResource method along with a various other places in the get method, but I get the error Failed to Load Pdf Document
I also tried adding it here like:
var resource = $resource('url', {},{responseType: 'arraybuffer'});
but this doesn't work as well
Full code:
function getResource(endpoint) {
var resource = $resource(endpoint, null);
return wrapActions(resource);
}
function wrapActions(resource) {
var wrappedResource = resource;
for (var i = 0; i < self.actions.length; i++) {
self.wrapAction(wrappedResource, self.actions[i]);
}
// return modified copy of resource
return wrappedResource;
}
function wrapAction(resource, action) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original and sending token
resource[action] = function (data, success, error) {
data = data || {};
return resource['_' + action](
angular.extend({}, data),
function (response) {
handleSuccess(response, success);
},
function (response) {
handleError(response, error);
}
);
};
}
function handleSuccess(response, callback) {
if (callback) {
callback(response);
}
}
function handleError(response, callback) {
if (typeof response.status !== 'undefined') {
switch (response.status) {
case '403' :
case 403 :
case '401' :
case 401 :
handle401();
return;
}
}
if (callback) {
callback(response);
}
}
function handle401() {
if ($state.current.name != 'login') {
AuthService.setRedirect($state.current.name, $stateParams);
}
AuthService.logout();
$state.go('login');
}
}

400 bad request on post

Trying to send a request from my factory to the back end, getting the following error: POST http://localhost:8000/messages/58d4b22d57f49028608f7bf9 400 (Bad Request)
Factory:
app.factory('usersFactory', function ($http) {
var factory = {};
var current_user = [];
factory.login = function (data, callback) {
$http.post('/users/', data)
.then(function (response) {
current_user.push(response.data);
callback(current_user);
})
};
factory.getUser = function (callback) {
callback(current_user);
}
factory.destroy = function (callback) {
current_user = [];
callback();
}
factory.writePost = function (data) {
console.log(data);
console.log(current_user[0]._id)
$http.post('/messages/' + current_user[0]._id, data)
.then(function (response) {
$location.url('/wall');
})
}
return factory;
});
Server routes:
var wall = require('./../controllers/serverController.js')
module.exports = function(app){
app.post('/users/', function (request, response) {
wall.login(request, response);
});
app.post('/messsage/:id', function (request, response) {
wall.writeMessage(request, response);
})
}
Sever controller:
module.exports =
{
writeMessage: function (request, response) {
User.findOne({ _id: request.params.id }, function (err, user) {
var message = new Message({ message: request.body, _user: request.params.id });
message.save(function (err) {
user.messages.push(message);
user.save(function (err) {
if (err) {
response.json(err);
}
})
})
})
}
}
this is error of sever side not angular, try to check logs of server.
Also you are using Message , do have schema imported in that ?

Find and save loop (MongoDB Node Express)

I have this controller which fetch data from instagram api.
controller.prototype.getData = function getData(url, tag, callback) {
var clientId = '81e3d3f35c8a4438964001decaa5a31f'
var catchAll = [];
var config = {
'params': {
'client_id': clientId,
'callback': 'JSON_CALLBACK'
}
}
vm.url = 'https://api.instagram.com/v1/tags/' + tag + '/media/recent/';
http.jsonp(url, config)
.then(function(response) {
vm.imageData = vm.imageData.concat(response.data.data);
vm.instagram.storeData(vm.imageData).then(function(response) {
})
var paging = response.data.pagination;
if (paging.hasOwnProperty('next_url')) {
getData(paging.next_url)
} else {
callback.call();
}
})
}
then on node mongodb controller i have this
exports.create = function(req, res) {
var dataObj = req.body;
dataObj.forEach(function(item) {
Data.find({
'id': item.id
}, function(err, data) {
if (err) {
return handleError(res, err);
}
if (data.length == 0) {
Data.create(item, function(err, data) {
if (err) {
return handleError(res, err);
}
});
}
});
});
};
The logic here is that if user is not existing in the collection i will save it. my question is why is it that it takes too long to response if have lets say 300 instagram object ? is there a ways how to do this in optimal performance?

How to use multiple factories in Angular to access uid sent from server

I am creating and sending a UID on the server side to the client side when the user visits a web page. I would like to use that UID as the subfolder to store each project a particular user posts to the server. I'm trying to figure out how best to accomplish this. When I use the code below, I am unable to access the UID in the Projects factory from the UserFactory.
Javascript (Angular):
myApp.factory('UserFactory', function UserFactory($http, API_URL, AuthTokenFactory, $q) {
return $http.get(API_URL + '/api/authenticate').then(function success(response) {
AuthTokenFactory.setToken(response.data.token);
return response;
});
});
myApp.factory('AuthTokenFactory', function AuthTokenFactory($window) {
var store = $window.localStorage;
var key = 'auth-token';
return {
getToken: getToken,
setToken: setToken
};
function getToken() {
return store.getItem(key);
}
function setToken(token) {
if (token) {
store.setItem(key, token);
} else {
store.removeItem(key);
}
}
});
myApp.factory('Projects', function($http, API_URL, UserFactory, AuthTokenFactory) {
var uid = UserFactory.response.data.token
var Projects = {
};
Projects.get = function(id) {
return $http.get(API_URL + '/api/projects/' + uid + id);
};
Projects.create = function(userData) {
return $http.post(API_URL + '/api/projects/' + uid, userData).then(function error(response) {
var data = response.data;
});
};
return Projects;
});
Node
apiRouter.get('/authenticate', function(req, res) {
var uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
var token = jwt.sign({
uid: uid
}, superSecret, {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
message: 'Enjoy your token!',
uid: uid,
token: token
});
});

angular, node + Service that returns SQL Data as json

Total newbee here. Given this service.js how can I go about returning terms data from sql server
app.service('termsService', function () {
this.getTerms = function () {
return terms
};
var terms = [
{
termid: 11, term: 'Shanika', termDefinition: 'Passmore'
}
];
});
The code below works well on its own so I want to return terms data in the service call above
var sql = require('msnodesql')
, nconf = require('nconf')
,express = require('express');
nconf.env()
.file({ file: 'config.json' });
var connectionString = nconf.get("SQL_CONN");
var app = express();
app.configure(function () {
app.use(express.bodyParser());
});
app.get("/", function(req, res) {
sql.open(connectionString, function(err, conn) {
if(err) {
}
else {
conn.queryRaw("SELECT TOP 10 termid, term, termDefinition FROM Terms", function(err, results) {
if(err) {
}
else {
res.json(results);
}
});
}
});
});
app.listen(3000);
A code for your angular service :
function Service($http) {
var Service = {};
Service.getCriteria = function (criteria,callback) {
$http({
url: "YOUR URL",
params: criteria,
method: "GET",
isArray: true
}).success(callback)
}
return Service;
}
Be aware of that is an async call, so use promises, callback or sync methods.

Resources