I want to delete all data in my database by a single click.but it gives
"DELETE http://localhost:8080/api/deleteAll 404 (Not Found)".
Can anyone help with this?
Below codes are my attempt.
Controller
$scope.deleteAllData = function () {
Event.deleteAll()
.success(function(){
console.log("All Deleted");
})
.error(function (error) {
$scope.status = 'Unable to load event data: ';
});
};
Service
deleteAll : function() {
return $http.delete('/api/deleteAll');
},
Route
var filesReadUploads = require('./models/readUploadFile');
app.delete('/api/deleteAll', function(req, res) {
filesReadUploads.remove({},function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
});
});
Thanks
Related
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 ?
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 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);
}
});
});
}
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
Here i need to search name in scroll,for that i send search data query string in get call but i need to that in post.
Here is my server and client controller route and service.Also here i handling search from server side.How to post data which user has been searched ,and pass that to client and server side.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {
},
searchUsers:{
method: 'GET',
}
});
}
]);
Angular controller:
$scope.searchServer = function(searchData){
DetailService.searchUsers({search:searchData},function(response){
}, function(error){
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller:
exports.searchCust = function (req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function (customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.jsonp(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.get(details.searchCust);
app.param('search', details.searchCust);
};
I didn't try it out in all details as it looks like it was copy and pasted together without reading the basics. However, if you want POST requests, you need to set them both in the node-code and the Angular code, see below. What's more, Angular doesn't use JSONP, it uses JSON, so you need to set that. In the searchUsers-resource-call you only implemented the error-branch, so the results would just vanish. You'll find them in $scope.searchResults now.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {},
searchUsers: {
method: 'POST',
}
});
}]);
Angular controller:
$scope.searchServer = function(searchData) {
DetailService.searchUsers({
search: searchData
}, function(response) {
$scope.status = "OK";
$scope.searchResults = response;
}, function(error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller
exports.searchCust = function(req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function(customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.json(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.post(details.searchCust);
app.param('search', details.searchCust);
};