I've node on server and Angular on client...
angular routes:
var todoApp = angular.module('todoApp', ['ngResource', 'ngRoute', 'ngCookies'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'templates/index.html'
});
$routeProvider.when('/todo',
{
templateUrl: 'templates/todo.html',
controller:"TodoController"
});
$routeProvider.when('/admin',
{
templateUrl: 'templates/admin.html'
});
$routeProvider.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
});
on server side I've defined a route for '/todo'
app.use('/todo', todo);
and My todo File is
var express = require('express'),
router = express.Router(),
todo = require('../controllers/todo'),
winston = require('../../server/config/winston');
// GET users listing.
router.get('/', todo.list);
router.post('/:id', todo.save);
router.delete('/:id', todo.delete);
module.exports = router;
My Problem
if I go to home page it works fine and data shows along with loaded Pages i.e if I Enter localhost/3000/ then by default it redirects to /todo and works perfectly.
If i enter localhost/3000/todo then i only see plain text on page that is data returned from server rather then HTML page that i can see above.
I don't know whats wrong with it...
Edit
My Todo Controller
var db = require('../config/sequelize'),
StandardError = require('standard-error');
var winston = require('winston');
exports.save = function (req, res) {
if (!req.user) {
return res.send("Please Login");
}
console.log("in create", req.body);
var _task = {
task: req.body.task,
UserId: req.user.id
}
console.log(req.user);
db.Todo.create(_task).then(function (todo) {
if (!todo) {
return res.send(new StandardError('Cannot insert'));
} else {
console.log(req.body);
return res.send(todo);
}
}).catch(function (err) {
return res.send({
errors: err,
status: 500
});
});
};
exports.list = function (req, res) {
if (!req.user || req.user.isAdmin) {
return res.redirect('/');
}
console.log(db.User);
db.Todo.findAll({where: {UserId: req.user.id}}).then(function (todo) {
console.log(todo);
res.jsonp(todo);
}).catch(function (err) {
console.log(err)
res.send([{task: "No Data"}]);
});
};
exports.delete = function (req, res) {
db.Todo.destroy({
where: {
id: req.params.id,
UserId: req.user.id
}
}).then(function (response) {
console.log("deleted");
res.send(response + " Record Deleted");
//db.Todo.findAll().then(function (todo) {
// res.jsonp(todo);
// }).catch(function (err) {
// return res.render('error', {
// error: err,
// status: 500
// });
// });
});
};
May be you are confused with the angular routes and the server routes.
Use localhost/#!/todo for your todo template and localhost/todo for invoking server
Related
id i m getting in the controller but its nt coming in the server,when i am clicking on delete i am getting the id in console. its showing error "possibly unhandled rejection" and error 404
this is my server:-
var express=require('express');
var mongojs=require('mongojs');
var bodyParser=require('body-parser');
var app=express();
var db=mongojs('contactlist',['contactlist']);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/Contactlist',function (req,res) {
console.log("ireceived a get request")
db.contactlist.find(function (err,docs) {
console.log(docs);
res.json(docs);
})
})
app.post('/Contactlist',function (req,res) {
db.contactlist.insert(req.body,function (err,doc) {
res.json(doc);
console.log(doc);
})
})
app.delete('/contactlist/:id',function (req,res) {
var id= req.params.id;
console.log(id);
})
app.listen(3000);
console.log('Server running on port 3000');
this is my controller
var ContactListApp = angular.module('ContactListApp',[]);
ContactListApp.controller('AppCtrl',[ '$scope','$http',function($scope,$http) {
console.log("controller");
var refresh=function () {
$http.get('/Contactlist').then(success,error)
function success(response) {
console.log(response,"I got the data i requested")
$scope.Contactlist=response.data;
}
function error(response){
alert("Please check your code");
}
};
refresh();
$scope.addContact=function () {
console.log($scope.contact);
$http.post('/Contactlist',$scope.contact).then(success,error)
function success(response) {
console.log(response);
$scope.Contactlist=response.data;
refresh();
};
function error() {
alert('error occured');
}
$scope.contact =null;
}
$scope.remove=function (id) {
console.log(id);
$http.delete('/contactlist/',id);
refresh();
}
}]);
I think you should try calling it like this
$http.delete('/contactlist/'+id);
if you are getting ID here
var id= req.params.id;
console.log(id);
then simply run query
db.contactlist.remove({_id:id},function (err,doc) {
if(err){ console.log("err n remove")}
else{console.log("Remove Success")}
})
I'm new to using the MEAN stack, have learned some of the basics to add data to mongodb using mongoose, express, and ui-router. However, I can't figure out how to delete a document. Whenever I try, I get 404 errors, even though it looks like the link should be correct. Would someone please help? Be kind, my code might be way off...
Here is my angular file:
var app = angular.module('updateTracker', ['ui.router']);
app.factory('courses', ['$http', function($http){
var o = {
courses: []
};
o.getAll = function() {
return $http.get('/courses').success(function(data){
angular.copy(data, o.courses);
});
};
o.create = function(course) {
return $http.post('/courses', course).success(function(data){
o.courses.push(data);
});
};
o.get = function(id) {
return $http.get('/courses/' + id).then(function(res){
return res.data;
});
};
o.addEntry = function(id, entry) {
return $http.post('/courses/' + id + '/entries', entry);
};
o.changeLesson = function(course) {
return $http.put('/courses/' + course._id + '/changeLesson')
.success(function(data){
course.lesson = "New Lesson";
});
};
o.removeCourse = function(course) {
return $http.delete('/courses/' + course._id + '/removeCourse')
.success(function (data, status) {
console.log(data);
});
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'courses',
function($scope, courses){
$scope.courses = courses.courses;
$scope.addCourse = function(){
if(!$scope.lesson || $scope.lesson === '') { return; }
courses.create({
lesson: $scope.lesson,
course: $scope.course,
curriculum: $scope.curriculum
});
$scope.lesson = '';
$scope.course = '';
$scope.curriculum = '';
};
$scope.changeLesson = function(course){
courses.changeLesson(course);
};
$scope.removeCourse = function(course) {
courses.removeCourse(course);
};
}]);
app.controller('CoursesCtrl', [
'$scope',
'courses',
'course',
function($scope, courses, course){
$scope.course = course;
$scope.addEntry = function(){
// if($scope.version === '') { return; }
courses.addEntry(course._id, {
version: $scope.version,
notes: $scope.notes,
statusCode: $scope.statusCode,
statusMessage: $scope.statusMessage,
author: 'user'
}).success(function(entry) {
$scope.course.entries.push(entry);
});
$scope.version = '';
$scope.notes = '';
$scope.statusCode = '';
$scope.statusMessage = '';
};
}]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['courses', function(courses){
return courses.getAll();
}]
}
})
.state('courses', {
url: '/courses/{id}',
templateUrl: '/courses.html',
controller: 'CoursesCtrl',
resolve: {
course: ['$stateParams', 'courses', function($stateParams, courses) {
return courses.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home')
}]);
My routes:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Course = mongoose.model('Course');
var Entry = mongoose.model('Entry');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
router.get('/courses', function(req, res, next) {
Course.find(function(err, courses) {
if(err){ return next(err); }
res.json(courses);
});
});
router.post('/courses', function(req, res, next) {
var course = new Course(req.body);
course.save(function(err, course) {
if(err){return next(err); }
res.json(course);
});
});
router.param('course', function(req, res, next, id) {
var query = Course.findById(id);
query.exec(function (err, course){
if (err) { return next(err); }
if (!course) { return next(new Error('can\'t find course')); }
req.course = course;
return next();
});
});
router.get('/courses/:course', function(req, res, next) {
req.course.populate('entries', function(err, course) {
if (err) { return next(err); }
res.json(course);
});
});
router.post('/courses/:course/entries', function(req, res, next) {
var entry = new Entry(req.body);
entry.course = req.course;
entry.save(function(err, entry){
if(err){ return next(err); }
req.course.entries.push(entry);
req.course.save(function(err, course) {
if(err){ return next(err); }
res.json(entry);
});
});
});
router.put('/courses/:course/changeLesson', function(req, res, next) {
req.course.changeLesson(function(err, course){
if (err) { return next(err); }
res.json(course);
});
});
router.delete('courses/:course', function(req, res) {
Course.remove({
_id : mongodb.ObjectID(req.params.course)
}, function(err) {
if(err) { res.send(err);}
console.log("remove id");
})
});
router.param('entry', function(req, res, next, id) {
var query = Entry.findById(id);
query.exec(function (err, entry){
if (err) { return next(err); }
if (!entry) { return next(new Error('can\'t find entry')); }
req.entry = entry;
return next();
});
});
and my course Schema:
var mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
lesson: String,
course: String,
curriculum: String,
entries: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Entry'}]
});
CourseSchema.methods.changeLesson = function(cb) {
this.lesson = "Update Lesson";
this.save(cb);
};
mongoose.model('Course', CourseSchema);
You forgot to add / in the begining of router.delete and /removeCourse at end as well as did not return value using either res.send or res.json or res.end, etc. This should be like bellow
router.delete('/courses/:course/removeCourse', function(req, res) {
Course.remove({
_id : req.params.course
}, function(err) {
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.json({});
console.log("remove id");
}
})
});
I'm trying to insert a details page of each of my captures using my service.
Though when I try loading the page with an id in my service (example: /capture/5740c1eae324ae1f19b7fc30) I get undefined, using this code:
app.factory('captureApi', ['$http', function($http){
var urlBase = 'URL';
// ==> Gives back an array as such:
//[
//{
// "_id": "5740c1e3e324ae1f19b7fc2f",
// "created_at": "2016-05-21T20:15:38.554Z",
// "userId": "118000609287736585411",
// "place": "place",
// "birdname": "birdname",
// "__v": 0
//},
//{
// "_id": "5740c1eae324ae1f19b7fc30",
// "created_at": "2016-05-21T20:15:38.554Z",
// "userId": "118000609287736585411",
// "place": "place",
// "birdname": "birdname",
// "__v": 0
//},
//{
// ...
//}
//]
return {
getAllCaptures : function () {
return $http.get(urlBase);
},
insertCapture : function(data) {
return $http.post(urlBase, data);
},
findCapture : function(id) {
//both give undefined
console.log(_.find(urlBase, function(capture){return capture._id == id}));
console.log(_.find(urlBase, function(capture){return capture.id == id}));
return _.find(urlBase, function(capture){return capture.id == id});
}
}
}]);
On the server side I am using mongoose/mongodb:
-route:
var Capture = require('../models/capture');
module.exports = function(router) {
router.post('/captures', function(req, res){
var capture = new Capture();
capture.birdname = req.body.birdname;
capture.place = req.body.place;
capture.userId = req.body.userId;
capture.author = req.body.author;
capture.picture = req.body.picture;
capture.created_at = new Date();
capture.save(function(err, data){
if(err)
throw err;
console.log(req.body);
res.json(data);
});
});
router.get('/captures', function(req, res){
Capture.find({}, function(err, data){
res.json(data);
});
});
router.delete('/captures', function(req, res){
Capture.remove({}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
router.get('/captures/:id', function(req, res){
Capture.findOne({_id: req.params.id}, function(err, data){
res.json(data);
});
});
router.delete('/captures/:id', function(req, res){
Capture.remove({_id: req.params.id}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
// router.post('/captures/:id', function(req, res){
// Capture.findOne({_id: req.params.id}, function(err, data){
// var capture = data;
// capture.birdname = req.body.birdname;
// capture.place.city = req.body.place.city;
// capture.place.country = req.body.place.country;
// capture.save(function(err, data){
// if(err)
// throw err;
// res.json(data);
// });
// })
// })
}
-model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = mongoose.Schema({
birdname: {type: String, required: true},
place: {type: String, required: true},
userId: {type: String, required: true},
author: {type: String, required: true},
picture: Schema.Types.Mixed,
created_at: Date
});
module.exports = mongoose.model('Capture', captureSchema)
Here is my server.js (extra info):
// Init Express Web Framework
var express = require('express');
var app = express();
var path = require('path');
// Set view engine to EJS & set views directory
app.set('view engine', 'ejs');
app.set('views', path.resolve(__dirname, 'client', 'views'));
app.use(express.static(path.resolve(__dirname, 'client')));
// Database Connection
var mongoose = require('mongoose');
var configDB = require('./server/config/database.js');
mongoose.connect(configDB.url);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: 'application/json'}));
// Main route
app.get('/', function(req, res){
res.render('index.ejs');
});
// // catch 404 and forwarding to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// API
var api = express.Router();
require('./server/routes/capture')(api);
app.use('/api', api);
// Set routes to other pages
app.get('/*', function(req, res){
res.render('index.ejs');
});
// Port Settings
app.listen(process.env.PORT || 3000, process.env.IP);
console.log('Listening on port ' + process.env.PORT);
On the client side I have the following the trigger the page:
$stateProvider
.state('home', {
url: '/',
templateUrl: 'partials/home.html',
controller: 'homeCtrl',
data: {
requiresLogin: false
},
resolve: {
$title: function() { return 'Home'; }
}
})
.state('dash', {
url: '/dashboard',
templateUrl: 'partials/dashboard.html',
controller: 'dashCtrl',
data: {
requiresLogin: true
},
resolve: {
$title: function() { return 'Dashboard'; }
}
})
.state('capture', {
url: '/capture',
templateUrl: 'partials/capture.html',
controller: 'captureCtrl',
data: {
requiresLogin: true
},
resolve: {
$title: function() { return 'Capture'; }
}
})
.state('viewCapture', {
url: '/capture/:id',
templateUrl: 'partials/viewCapture.html',
controller: 'viewCaptureCtrl',
data: {
requiresLogin: true
},
resolve: {
$title: function() { return 'Capture Detail'; }
}
})
viewCaptureCtrl.js:
app.controller('viewCaptureCtrl', ['$scope', 'captureApi', '$stateParams', '$http', function($scope, captureApi, $stateParams, $http) {
var id = $stateParams.id;
$scope.viewCapture = function() {
captureApi.findCapture(id)
.then(function(data) {
$scope.capture = data;
});
};
$scope.viewCapture();
}]);
Anyone have an idea why my find function is giving an undefined?
Help is much appreciated! Thanks
You'll need to reference underscoreJS and inject it into your service. Document: http://app-genesis.com/underscorejswithangularjs/
var app = angular.module("app", []);
app.factory('_', function() { return window._; });
//inject into capture api factory
app.factory('captureApi', ['$http', '_', function($http, _){
//do stuff with _
}]);
Edit: But I'm not familiar with _.find(); if it returns a promise or not. If not, you'll need to make use of $q to create a promise and return it in order to use then().
//inject into capture api factory
app.factory('captureApi', ['$http', '_', '$q',
function($http, _, $q) {
return {
findCapture: function(id) {
var deferred = $q.defer();
try {
var results = _.find(); //do stuff with _
deferred.resolve(results);
} catch (err) {
deferred.reject(err);
}
//you need to return a promise in order to use then()
return deferred.promise;
}
}
}
]);
I have an Edit button on my event-detail page that goes to a new page where user can update the current selected event. I have no trouble using GET to get single/all events and POST to create new event. But I'm stuck on updating existing event and constantly get 404 error: PUT http://localhost:3000/api/events 404 (Not Found)
On my server route I have:
//return event-details
app.get('/api/events/:id', events.getEventById);
//update event
app.put('/api/events/:id', events.updateCurrentEvent);
Server side event controller:
exports.updateCurrentEvent = function(req, res) {
Event.findById(req.params.id, req.body, function(err, event) {
var event = req.body;
if(!event) {
res.statusCode = 404;
res.send({ error: 'Not found'});
}
event.title = req.body.title;
event.desc = req.body.desc;
event.date = req.body.date;
event.duration = req.body.duration;
event.address = req.body.address;
event.city = req.body.city;
event.state = req.body.state;
event.save(function (err) {
if (!err) {
log.info("event updated");
res.send({ status: 'OK', event:event });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
log.error('Internal error(%d): %s',res.statusCode,err.message);
}
});
});
My $resource service:
app.factory('mvEvent', function($resource) {
var EventResource = $resource('/api/events/:_id', {_id: "#id"}, {
update: {method:'PUT', isArray:false}
});
return EventResource;
});
my client-side controller:
angular.module('app').controller('mvUpdateEventCtrl', function($scope, $routeParams, $location, mvEvent) {
$scope.event = mvEvent.get({_id:$routeParams.id})
.$promise
.then(function(event) {
$scope.event = event;
console.log($scope.event);
$scope.title =$scope.event.title;
$scope.desc = $scope.event.desc;
$scope.date = $scope.event.date;
$scope.duration = $scope.event.duration;
$scope.address = $scope.event.address;
$scope.city = $scope.event.city;
$scope.state = $scope.event.state;
});
$scope.updateEvent = function() {
$scope.event.$update(function() {
}, function(error) {
$scope.error = error.data.message;
});
}
});
My client side routes:
var app = angular.module('app', ['ngResource', 'ngRoute', 'ui.bootstrap']);
app.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
//events route
.when('/events', {
templateUrl: '/partials/events/event-list',
controller: 'mvEventListCtrl'
})
//events detail route
.when('/events/:id', {
templateUrl: '/partials/events/event-details',
controller: 'mvEventDetailsCtrl'
})
//update event route
.when('/events/:id/update', {
templateUrl: '/partials/admin/event-update',
controller: 'mvUpdateEventCtrl'
})
});
Getting the event details showing in the each text field is as far as I can get. As soon as I hit 'Update event' Button I get 404 error and it seems to lie somewhere in my server side code. I've seen quite a bit of different approaches implementing PUT request, with or without routeParams, using findById then save or findByIdAndUpdate. I'm wondering if there is a standard way to do this. Thanks in advance!!
Remove the line var event = req.body; from your server side controller. Firstly, it is not required. Secondly, it is same as the name of the document returned by Event.findById callback, and that's getting overridden by the variable declaration.
exports.updateCurrentEvent = function(req, res) {
Event.findById(req.params.id, req.body, function(err, event) {
var event = req.body; // <<==== Remove this line
if(!event) {
res.statusCode = 404;
res.send({ error: 'Not found'});
}
event.title = req.body.title;
event.desc = req.body.desc;
event.date = req.body.date;
event.duration = req.body.duration;
event.address = req.body.address;
event.city = req.body.city;
event.state = req.body.state;
event.save(function (err) {
if (!err) {
log.info("event updated");
res.send({ status: 'OK', event:event });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
log.error('Internal error(%d): %s',res.statusCode,err.message);
}
});
});
}
This is my Server.js file (NodeJS):
var express = require('express');
var server= require('http');
var path= require("path");
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app= express();
var staticDIR = path.resolve(__dirname, "./www");``
app.use(express.static(staticDIR));
app.use(bodyParser.json());
app.get("*", function (req, res) {
var indexViewPath = path.resolve(__dirname, "./www/index.html");
res.sendFile(indexViewPath);
});
var dbURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected through app termination');
process.exit(0);
});
});
var userSchema = new mongoose.Schema({
name: String,
password:String,
email: {type: String, unique:true},
createdOn: { type: Date, default: Date.now }
//modifiedOn: Date,
//lastLogin: Date
});
mongoose.model( 'User', userSchema );
var User = mongoose.model('User');
var CompanySchema = new mongoose.Schema({
CompanyName: String,
password:String,
email: {type: String, unique:true},
createdOn: { type: Date, default: Date.now }
//modifiedOn: Date,
//lastLogin: Date
});
mongoose.model( 'company', userSchema );
var company = mongoose.model('company');
User.find({}, function(err, users) {
if(!err){
console.log(users);
}
});
company.find({}, function(err, users) {
if(!err){
console.log(users);
}
});
app.post('/account', function(req, res){
new company({
CompanyName:req.body.Company,
email:req.body.email,
password:req.body.password
}).save(function(err,doc){
if(err)res.json(err);
else res.send("succesfully inserted");
console.log(res);
});
});
This is my Middleware to get tha data:
app.get('/details', function (req, res) {
console.log('I received a GET request');
company.find({}, function(err, users) {
if(!err){
console.log(users);
}
else{
res.render('/details',{users:docs})
}
});
});
app.listen(9000);
console.log("Server Running on port 3000");
This is my Controller.js (AngularJS) file:
angular.module('myApp', ['ngMaterial','firebase','ui.router'])
.controller('detailsCtrl', function($scope,myfirebaseAddress,$location,$timeout) {
var ref = new Firebase(myfirebaseAddress);
})
This is my route where I want to show the mongoDb saved data
<ui-view>
<div class="sub-header">
<h3>Company Details</h3>
</div>
<ul>
<li ng-repeat="users in user">
{{user.email}}
</li>
</ul>
</ui-view>
Thanks in advance
instead if writing below code
if(!err){
console.log(users);
}
else{
res.render('/details',{users:docs})
}
do like this
if(!err){
res.send(users);
}
else{
res.send('could not retrived data');
}
in controller side you can get your all data inside success call back function.here also check
app.listen(9000);
console.log("Server Running on port 3000");
this should like below.
app.listen(9000);
console.log("Server Running on port 9000");
Controller to get the requested data
.controller('detailsCtrl', function($scope,$http) {
$scope.users = [];
$http.get('/details').then(function(d)
{
console.log(d);
$scope.users= d.data;
},function(err)
{
console.log(err); }
)
})
server route
app.get('/details', function (req, res) {
console.log('I received a GET request');
company.find({}, function(err, users) {
if(!err){
res.json(users);
}
});
});
If you want to retrieve your data, you must stop this:
res.render('/details',{users:docs})
If you want to serve data with an angular app, you have to stop to render a view and start to give back a json in your response.
res.jsonp(users)
Then you've to adjust your controller.
Write a service like:
angular.module('yourApp')
.service('userService', function($http){
return {
getUsers: function(url) {
return $http.get(url)
}
}
})
this should return an http promise.
In your controller you handle this promise this way:
$scope.users = function(){
userService.getUsers('/users')
.then(function(users){
//You have your users object
})
}
remember to handle the unsuccesfull case of your promise
Try to use the angular http module to get the node/express response that get the data from mongodb in client side; like this: https://github.com/J-Alex/api_rest_mvc