$http.delete returns error 404 - angularjs

I am new to Angular and I'm trying to build a CRUD using the MEAN stack.
Yet I am having trouble with Angular to call the DELETE function on the server side.
Here is my Angular App.JS
var app = angular.module('topshelf', [])
app.controller('MainCtrl', [
'$scope','$http',
function($scope , $http){
var Mydata = {};
$http.get("http://localhost:8080/inventory").success(function(data,status,header,config){
$scope.Mydata = data;
});
$scope.delete = function($index) {
var url = "http://localhost:8080/ingredients/" + $index;
$http.delete(url).success(function(err,data){
if (err){ console.log(err);}
$scope.Mydata = data;
console.log("test");
});
}
}]);
and here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TopShelf</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="./app.js"></script>
</head>
<body ng-app ="topshelf" ng-controller="MainCtrl" class="top-navigation">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Ingredient</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ingredients in Mydata">
<td>{{ingredients.name}} </td>
<td>{{ingredients.quantity}} </td>
<td> Add / Edit / <a ng-click="delete($index)">Delete</a></form></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
UPDATE
Also, here is my server code specifying the routes though when I try the routes with POSTMAN it works fine.:
var express = require('express');
var Ingredients = require('./models/ingredients.js');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/labelleassiette');
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.sendFile(__dirname+"/public/index.html");
})
app.get('/inventory',function(req,res){
Ingredients.find(function(err,ingr){
res.json(ingr);
})
})
app.post('/add', function(req,res){
var entry = new Ingredients({name: req.body.name, quantity: req.body.quantity});
var self = this;
Ingredients.find({name:req.body.name}, function(err,data){
if(data.length){
res.send(500,"Ingredient exists!");
}
else{
entry.save(function(err){
if (err) {console.log(err);}
else { console.log('Saved to db')}
});
res.redirect('/');
}
})
})
app.put('/ingredients/:id',function(req,res) {
var id = req.params.id;
var obj = req.body;
Ingredients.findByIdAndUpdate(id, {name: obj.name, quantity: obj.quantity}, function(err){
if (err) {console.log(err);}
console.log("updated");
})
})
app.delete('/ingredients/:id',function(req,res){
Ingredients.findByIdAndRemove(req.params.id,function(err){
if (err) {console.log(err);}
console.log("effacé");
res.redirect('/');
})
})
app.listen(8080, function() {
console.log("listening on port 8080!");
});
i am getting a DELETE http://localhost:8080 404 not found on my browser's console.
Thank you guys for your help

Related

ng-repeat not binding from database

I have a 1 page application which should display a list of objects from a database. I used ng-repeat to create a template to bind data from array in db. As I am new to Angular any help would be great. My code is below:
SERVER.JS
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('eventlist', ['eventlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/eventlist', function (req, res) {
console.log("i received a get request")
db.eventlist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/eventlist', function (req, res){
console.log(req.body);
db.eventlist.insert(req.body, function (err, doc) {
res.json(doc);
});
});
app.delete('/eventlist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.eventlist.remove({_id: mongojs.ObjectID(id)}, function (err, doc) {
res.json(doc);
});
});
app.get('/eventlist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.eventlist.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
});
});
app.put('/eventlist/:id', function (req, res) {
var id = req.params.id;
console.log(req.body.name);
db.eventlist.findAndModify({
query: {_id: mongojs.ObjectId(id)},
update: {$set: {name: req.body.name, startDate: req.body.startDate, price: req.body.price, location: req.body.location}},
new: true}, function (err, doc) {
res.json(doc);
}
);
});
app.listen(4000);
console.log("Server running on port 4000");
INDEX.HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/page.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>Capstone Project</title>
<meta name="description" content="Carnival and Event Mapping tool">
<link rel="manifest" href="/manifest.json">
</head>
<body>
<div id="wrapper">
<div class="overlay"></div>
<!-- Sidebar -->
<nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
<ul class="nav sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Brand
</a>
</li>
<li>
Enter Zip Code
</li>
<li>
<input type="text"/><button>Submit</button>
</li>
<li class="dropdown">
Events Near Me<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li class="dropdown-header">Select Radius</li>
<li>5 Miles</li>
<li>10 Miles</li>
<li>15 Miles</li>
</ul>
</li>
<li>
Ascending
</li>
<li>
Descending
</li>
<li>
Contact
</li>
</ul>
</nav>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<button type="button" class="hamburger is-closed" data-toggle="offcanvas">
<span class="hamb-top"></span>
<span class="hamb-middle"></span>
<span class="hamb-bottom"></span>
</button>
<div class="container" ng-controller="AppCtrl">
<h1>Summer Event List</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Price</th>
<th>Location</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" ng-model="event.name"></td>
<td><input class="form-control" ng-model="event.startDate"></td> <!--type="date" (put this next to startDate)-->
<td><input class="form-control" ng-model="event.price"></td> <!--$<input type="number" name="currency" min="0" max="9999" step="0.01" size="4"
title="CDA Currency Format - no dollar sign and no comma(s) - cents (.##) are optional" />-->
<td><input class="form-control" ng-model="event.location"></td>
<td><button class="btn btn-primary" ng-click="addEvent()">Add Event</button></td>
<td><button class="btn btn-primary" ng-click="deselect()">Clear</button></td>
</tr>
<tr ng-repeat="event in eventlist"> <!--also tried ng-repeat="event in eventlist track by $indexs"-->
<td>{{event.name}}</td>
<td>{{event.startDate}}</td>
<td>{{event.price}}</td>
<td>{{event.location}}</td>
<!-- <td><button class="btn btn-danger" ng-click="remove(contact._id)">Remove</button></td>
<td><button class="btn btn-warning" ng-click="edit(contact._id)">Edit</button></td> -->
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js" charset="utf-8"></script>
<script src="controllers/controller.js" charset="utf-8"></script>
</body>
</html>
</div>
<!-- /#page-content-wrapper -->
<script>
$(document).ready(function () {
var trigger = $('.hamburger'),
overlay = $('.overlay'),
isClosed = false;
trigger.click(function () {
hamburger_cross();
});
function hamburger_cross() {
if (isClosed == true) {
overlay.hide();
trigger.removeClass('is-open');
trigger.addClass('is-closed');
isClosed = false;
} else {
overlay.show();
trigger.removeClass('is-closed');
trigger.addClass('is-open');
isClosed = true;
}
}
$('[data-toggle="offcanvas"]').click(function () {
$('#wrapper').toggleClass('toggled');
});
});
</script>
</body>
</html>
CONTROLLER.JS
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
var refresh = function(){
$http.get('/eventlist/').then(function(response) {
console.log("I got the data I requested");
$scope.eventlist = response;
$scope.event = null;
});
};
refresh();
$scope.addEvent = function () {
console.log($scope.event);
$http.post('/eventlist/', $scope.event).then(function(response){
console.log(response);
refresh();
});
$scope.update = function() {
console.log($scope.event._id);
$http.put('/eventlist/' + $scope.event._id, $scope.event).then(function(response) {
refresh();
})
};
};
$scope.remove = function(id) {
console.log(id);
$http.delete('/eventlist/' + id).then(function(response) {
refresh();
});
};
$scope.edit = function(id) {
console.log(id);
$http.get('/eventlist/' + id).then(function(response) {
$scope.event = response;
});
};
$scope.deselect = function() {
$scope.event = null;
refresh();
};
}]);
Change it as response.data,
var refresh = function(){
$http.get('/eventlist/').then(function(response) {
$scope.eventlist = response.data;
$scope.event = null;
});
};

Configure ngRoute with $http

I am trying to confugure ngRoute with $http and I am getting error in console when i go to website: localhost:8080
Uncaught ReferenceError: angularModule is not defined(anonymous
function) # item_controller.js:2
angular.js:38Uncaught Error:
[$injector:modulerr]
http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=myApp&p1=Error%3A%2…2Flocalhost%3A8080%2Fbower_components%2Fangular%2Fangular.min.js%3A21%3A19)
When I open http://localhost:8080/home then I see "Whitable error page". I am writeing my API in Spring framework (Spring-boot)
How should I configure these two things to work properly? I cant find any good example how should i write this in good way.
My configuration looks like below:
app.js
'use strict';
var App = angular.module('myApp', ['ngRoute', 'moduleItemController']);
App.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when( '/home', {
templateUrl: '../item.html',
controller: 'ItemController'
}).
when('/item/:itemCode',{
templateUrl: '../../templates/item-detail.html',
controller: 'ItemController'
}).otherwise({
redirectTo: '/home'
});
}]);
item_controller.js
'use strict';
var moduleItemController = angularModule.module('moduleItemController',[])
moduleItemController.controller('ItemController', ['$scope', 'ItemService', function ($scope, ItemService) {
var self = this;
self.item = {id: null, itemCode: '', itemName: '', price: ''};
self.items = [];
self.fetchAllItems = function () {
ItemService.fetchAllItems()
.then(
function (d) {
self.items = d;
},
function (errResponse) {
console.error('Error while fetching Currencies');
}
);
};
self.createItem = function (item) {
ItemService.createItem(item)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while creating item.');
}
);
};
self.updateItem = function (item, id) {
ItemService.updateItem(item, id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while updating item.');
}
);
};
self.deleteItem = function (id) {
ItemService.deleteItem(id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while deleting item.');
}
);
};
self.updatePrice = function (newPrice, item, id) {
ItemService.updatePrice(newPrice, item, id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while updating item.');
}
);
};
self.fetchAllItems();
self.submit = function () {
if (self.item.id === null) {
console.log('Saving New item', self.item);
self.createItem(self.item);
}
else {
console.log('Sth went wrong!');
}
self.reset();
};
self.remove = function (id) {
console.log('id to be deleted', id);
if (self.item.id === id) {
self.reset();
}
self.deleteItem(id);
};
self.reset = function () {
self.item = {id: null, itemCode: '', itemName: '', price: ''};
$scope.myForm.$setPristine();
};
}]);
moduleItemController.controller('ItemController', ['$scope','$routeParams', function ($scope,$routeParams) {
$scope.itemCode = $routeParams.itemCode;
}]);
item_service.js
App.factory('ItemService', ['$http', '$q', function ($http, $q) {
return {
fetchAllItems: function () {
return $http.get('http://localhost:8080/api/item/all')
.then(
function (response) {
return response.data;
console.success('Success');
},
function (errResponse) {
console.error('Error while fetching users');
return $q.reject(errResponse);
}
);
},
.
.
.
// other crud operations
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HOME</title>
<link rel="stylesheet" type="text/css" href="bower_components/semantic/dist/semantic.min.css">
<script src="bower_components/semantic/dist/semantic.js"></script>
<!--Angular dependencies-->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controller/item_controller.js"></script>
<script src="js/service/item_service.js"></script>
</head>
<body ng-app="myApp">
<div ng-view></div>
</body>
</html>
item.html -- here is part of this file where I want to use ngRoute
<table class="ui fixed table">
<thead>
<tr>
<th>Id</th>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th width="20%"></th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in ictrl.items | filter:query">
<td><span ng-bind="i.id"></span></td>
<td class="selectable">
<span ng-bind="i.itemCode"></span>
</td>
<td><span ng-bind="i.itemName"></span></td>
<td><span ng-bind="i.price"></span></td>
<td><span ng-bind="i.quantity"></span></td>
<td>
<button class="negative ui button" ng-click="ictrl.remove(i.id)">delete</button>
</td>
<td>
<button class="ui secondary button">zp</button>
</td>
</tr>
</tbody>
</table>
item-detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Details</title>
<!--SEMANTIC-->
<link rel="stylesheet" type="text/css" href="bower_components/semantic/dist/semantic.min.css">
<script src="bower_components/semantic/dist/semantic.js"></script>
<!--ANGULAR-->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controller/item_controller.js"></script>
<script src="js/service/item_service.js"></script>
</head>
<body ng-app="myApp">
<div class="item table container">
<h1>TBD DETAILED VIEW FOR {{itemCode}}</h1>
</div>
</body>
</html>
The problem is you are trying to use angularModule instead of angular in item_controller.js. The global object from angular.js is angular and not angularModule
Change the below line as:
var moduleItemController = angularModule.module('moduleItemController',[]);
to
var moduleItemController = angular.module('moduleItemController',[]);
Line 2 of item_controller.js is referencing angularModule.module which is undefined. I think you want angular.module.

Weird flow of simple mean stack application

Here is my implementation of simple mean stack application
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlistDB', ['contactlist']);
app.use(express.static(__dirname + "/public"));
app.get('/friendlist', function(req, res){
db.on('connect', function(){
console.log("DB connected !!!");
});
console.log("received GET request");
db.contactlist.find(function(err, docs){
res.send(docs);
});
});
app.listen(3000);
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
$http.get('/friendlist').success(function(response){
$scope.friendList = response;
})
}]);
index.html
<!DOCTYPE>
<html ng-app="myApp">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<title>Friends Information App</title>
<body>
<div class="container" ng-controller="AppCtrl">
<h1>Friend Information App</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Number</th>
</tr>
<tr ng-repeat="friend in friendList"> <!-- same as for loop -->
<th>{{friend.name}}</th>
<th>{{friend.email}}</th>
<th>{{friend.number}}</th>
</tr>
</thead>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</body>
</head>
</html>
Definitely my route is /friendlist but I do not know why, when I just hit thr url http://localhost:3000, all my friends information are shown up with the UI in index.html file. And when hitting the http://localhost:3000/friendlist, what I got just the json normal text without UI
Please help to explain to me about the workflow of this case.
Many thanks!
When you're hitting http://localhost:3000 you reach your web page which contains all your UI stuff. By hitting http://localhost:3000/friendlist, you're requesting your API which prints your JSON object. This is because you're serving your html by your API with the line app.use(express.static(__dirname + "/public"));. It's a normal behavior.
First of all
app.get('/friendlist', function(req, res){
db.on('connect', function(){
console.log("DB connected !!!");
});
console.log("received GET request");
db.contactlist.find(function(err, docs){
res.send(docs);
});
});
it is called which redirects to the get method in /friendlist controller function.
Under that
$http.get('/friendlist').success(function(response){
$scope.friendList = response;
})
it is called and it gives the response in friendlist var. and it prints out the thing accordingly.

ng-include not working for basic angular 1 code

Ok, there're many similar questions, i went through some and get me more confused, btw i started learning angular 1 about 2 weeks ago.
in browser, /mypath/status.html works fine, it sends "testJson" to node server, then
displays data to the webpage
now i have /mypath/index2.html, which ng-include status.html, it won't
trigger "testJson" in the server code
status.html
<!DOCTYPE html>
<html ng-app="HelloModule">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<body ng-controller="HelloCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/
angular.js"></script>
<script src="statusApp.js"></script>
<table>
<tr>
<th>Code</th>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries | orderBy: 'code' ">
<th>{{country.code}}</th>
<th>{{country.name}}</th>
<th>{{country.population}}</th>
</tr>
</table>
</body>
</html>
statusApp.js
var app = angular.module('HelloModule', []);
app.controller('HelloCtrl', function($scope, HelloService) {
//$scope.countries = [{code : "US", name : "United States", population : "11223344"}];
HelloService.getJson().then(function(result) {
$scope.countries = result;
}, function(error) {
alert("Error");
} );
});
app.factory('HelloService', function($http, $q) {
return {
getJson: function() {
var deferred = $q.defer();
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
var url = server + port + '/testJson';
//$http.get('http://localhost:7778/testJson').success(function(data) {
$http.get(url).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
}
});
index2.html which is not working,
i don't see this line
console.log("returning Json data");
triggered in the server
<!DOCTYPE html>
<html ng-app>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.
min.js"></script>
<div class="container">
<div ng-include="" src="'status.html'"></div>
</div>
</body>
</html>
server side
app.get('/testJson', function(req, res)
{
console.log("returning Json data");
res.json( [{code : "US", name : "United States", population : "11223344"
}] );
});
The status.html that you want to include is :
<table ng-controller="HelloCtrl" >
<tr>
<th>Code</th>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries | orderBy: 'code' ">
<th>{{country.code}}</th>
<th>{{country.name}}</th>
<th>{{country.population}}</th>
</tr>
</table>
Right ?
EDIT
And ng-include works like this :
<div class="container">
<div ng-include="'status.html'" ></div>
</div>

Angular - Data Returned But ng-repeat Not Displaying It

I'm having an issue where although my Angular JS is returning data from my backend, I can't get ng-repeat to display it. Here's my HTML file:
<!DOCTYPE html>
<html ng-app="docManager">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DocManCtrl as docs">
<div>
<input placeholder="Search" type="text" ng-model="searchKey" />
</div>
<table class="table">
<tr><th>Document ID</th><th>Filename</th><th>Category</th></tr>
<tr ng-repeat="document in docs.documents | filter:searchKey">
<td>{{document.id}}</td>
<td>{{document.filename}}</td>
<td>{{document.category}}</td>
</tr>
</table>
<button ng-click="docs.add()">Add Document</button>
</body>
And here is my JS file:
var app = angular.module('docManager', []);
app.controller('DocManCtrl', DocManCtrl);
function DocManCtrl($http){
$http.get('http://localhost:3000/documents').success(function(data){
this.documents = data;
console.log('Data retrieved.');
}).error(function(){
console.log('Error: could not GET documents');
});
}
DocManCtrl.prototype.add = function(){
console.log('Hello, world.');
};
I know my $http.get is working, because if I print out the contents of 'data' to the console, I see the data from my database. Anybody know where my mistake is?
Thanks!
Bryan
When you use this in your callback function it doesn't refer to your controller. So you'd have to do something like this:
function DocManCtrl($http) {
var self = this;
$http.get('http://localhost:3000/documents').success(function (data) {
self.documents = data;
});
}
var app = angular.module('docManager', []);
app.controller('DocManCtrl', DocManCtrl);
function DocManCtrl($http){
var vm = this;
$http.get('http://localhost:3000/documents').success(function(data){
vm.documents = data;
console.log('Data retrieved.');
}).error(function(){
console.log('Error: could not GET documents');
});
}
DocManCtrl.prototype.add = function(){
console.log('Hello, world.');
};

Resources