I am pretty new to AngularJS, and even newer to ExpressJS and Mongoose. I have been following a tutorial to post to, and get from my database, but I'm having trouble adding delete functionality.
Here is where I call my delete function:
<ul ng-repeat="disease in diseases">
<li>
{{ disease.name }}: {{ disease.chipped }},
{{ disease.received }},
{{ disease.smashed }},
{{ disease.complete }}
</li>
<button ng-click="removeDisease(disease)"></button>
</ul>
... and in my controller I have:
app.controller('MainCtrl', [
'$scope',
'TrelloApi',
'diseases',
function($scope, TrelloApi, diseases){
$scope.diseases = diseases.diseases;
$scope.removeDisease = function(disease) {
console.log(disease);
diseases.destroy(disease);
}
}
]);
...which calls my diseases factory:
app.factory('diseases', [
'$http',
function($http){
var o = {
diseases: []
};
o.destroy = function(disease) {
return $http.delete('/diseases/' + disease._id).success(function(data){
console.log("Disease " + disease.name + " has been removed!");
o.getAll();
});
};
return o;
}
]);
This returns with a 404 error:
DELETE http://localhost:4000/diseases/<id> 404 (Not Found) even though in my my routes include:
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Disease = mongoose.model('Disease');
// Not functional
router.delete('/diseases/:id', function(req, res, next) {
console.log(req);
});
// Functional
router.post('/diseases', function(req, res, next) {
var disease = new Disease(req.body);
disease.save(function(err, diseases){
if(err){ return next(err); }
res.json(diseases);
});
});
... and ui.router includes:
app.config([
'TrelloApiProvider',
'$stateProvider',
'$urlRouterProvider',
function(TrelloApiProvider, $stateProvider, $urlRouterProvider) {
.state('diseases', {
url: '/diseases/{id}',
templateUrl: '/javascripts/home/_diseases.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
]);
There is also a template found at /javascripts/home/_diseases.html. I have a feeling I am missing one piece but I just can't figure out what it is.
Be sure you start Express HTTP server:
const express = require('express');
const router = express.Router();
router.delete('/diseases/:id', function(req, res, next) {
const id = req.params.id;
console.log(id);
});
const app = express();
app.use('/', router);
const server = http.createServer(app).listen(8080, serverCallback);
function serverCallback() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server listening on ${host}:${port}`);
}
Related
I am creating a MEAN stack application using AngularJS and Node.js.
Here is my AngularJS code:
app.js:
var app = angular.module('crudApp', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider
.when('/employees/create', {
templateUrl : 'create.html',
controller : 'EmployeeController'
}).when('/nothing', {
templateUrl : 'main.html',
controller : 'mainController'
});
$locationProvider.html5Mode(true);
}]);
app.controller('EmployeeController',function($scope,$http) {
$scope.save = function(data) {
$scope.data = JSON.stringify(data);
console.log(data);
$http.post("http://localhost:8080/employees/create-employee",$scope.data).then(function(response) {
console.log("posted successfully");
});
};
});
Here is my Node.js code:
server.js:
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(__dirname + '/angularjs/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('*',function(req, res) {
res.sendFile(__dirname + '/angularjs/public/index.html');
});
require('./node/routes')(app);
app.listen(8080);
routes.js:
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.body);
});
Angular part is working fine, displays data in console, posting the data and getting "posted successfully" message.
But in node, I am unable to get the posted data in req.body.
I am getting the "create.html" content when I checked in browser "network".
Need someone's help.
Use this
module.exports = function(app) {
app.post('/employees/create-employee',function(req,res) {
console.log(req.body);
});
And for get you should use req.params
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.params);
});
I have a couple of simple routes that I have misconfigured and not sure why.
app.js:
//app setup
var http = require('http');
var bodyParser = require('body-parser');
var express = require('express');
var routes = require('./routes');
var agent = require('./routes/agent');
var config = require('./config');
var app = express();
app.server = http.createServer(app);
app.use(bodyParser.json({
limit : config.bodyLimit
}));
app.use(bodyParser.urlencoded({
extended : true
}));
app.use('/v1', routes);
app.use('/v1/agent', agent);
app.server.listen(config.port);
console.log('API listening on port ' + app.server.address().port);
module.exports = app;
This returns responses on the /v1/ route (index.js):
'use strict';
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.status(403).json({
message: 'Invalid request.'
});
});
module.exports = router;
in the agent route, I have a POST handler that is being handled correctly at /v1/agent/login. But while a GET routed at /v1/agent/ works, a GET routed to /v1/agent/123 returns a 404:
'use strict';
var agentController = require('../controller/agent.js');
var express = require('express');
var router = express.Router();
function handleError(objError, res) {
res.status(500).json({ errorMessage : objError.message });
}
router.get('/', function (req, res) {
res.status(200).json({
message: 'OK' // works fine
});
});
router.get('/:id'), function (req, res) {
var agentNum = req.params.id;
res.send(req.params); // 404 here
try {
//res.status(200).json({ message: 'hello agent.'});
} catch (err) {
// handleError(err, res);
}
};
router.post('/login', function (req, res) {
var agentNum, password;
// works fine
});
router.post('/pwr', function (req, res) {
//also works fine
});
module.exports = router;
My understanding is that the app.use method should redirect the route and any GET requests appended to that route to the one I specified (agent), so why is it that the one with params fails while the root one succeeds?
Thank you
You're not passing the callback correctly.
router.get('/:id')
router.get('/:id', function(req, res) {
var agentNum = req.params.id;
res.send(req.params); // 404 here
try {
//res.status(200).json({ message: 'hello agent.'});
} catch (err) {
// handleError(err, res);
}
});
I am building a simple MySQL, Express, Angular, Node app and using Sequelize as my ORM. When I create a new survey, the values I am sending do not get set, as the req.body is an empty object.
server.js
'use strict';
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var bodyParser = require('body-parser');
var models = require('./server/models/');
var routes = require('./server/routes');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(process.cwd() + '/public'));
//App routes
app.use(routes(express.Router()));
app.get('/*', function (req, res) {
res.sendFile('index.html', {
root: './public'
});
});
app.listen(port, function() {
console.log('Server running on port %s ', port);
});
app.js
'use strict';
// Declare app level module which depends on views, and components
var app = angular.module('myApp', []);
app.controller('SurveyController', ['$scope', '$http', function($scope, $http) {
//Get all Surveys
$http.get("/surveys")
.then(function(response) {
$scope.surveys = response.data;
});
$scope.create = function() {
$http.post("/surveys",{
question: $scope.question,
answers: $scope.answers,
user: $scope.user
})
.then(function(response) {
});
}
}]);
model
'use strict';
module.exports = function(sequelize, DataTypes) {
var Survey = sequelize.define('Survey', {
question: DataTypes.STRING,
answers: DataTypes.STRING,
user: DataTypes.STRING
}, {
underscored: true,
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Survey;
};
routes.js
var surveys = require('./controllers/surveys');
module.exports = function (router) {
//routes
router.get('/surveys', surveys.get);
router.get('/surveys/:id', surveys.getOne);
router.post('/surveys', surveys.create);
router.put('/surveys', surveys.update);
router.delete('/surveys', surveys.delete);
return router
};
controller
//Create a new survey
create: function(req, res) {
//this req.body and req.params are both empty
Survey.create(req.body)
.then( function(newSurvey) {
res.status(200).json(newSurvey);
})
.catch( function(error) {
res.status(500).json(error);
})
},
I recently had a similar problem here: Why is my req.body always empty on POST? but the solution for that did not work for this issue. I am presuming it is similar but the solution has alluded me so far.
Don't need to stringify
$http
.post("/surveys", {
question: $scope.question,
answers: $scope.answers,
user: $scope.user
},
{
headers: { 'Content-Type': 'application/json; charset=UTF-8'}
})
Per many comments above (many thanks to all), I solved this by changing my bodyParser implementation from
app.use(bodyParser.urlencoded({
extended: true
}));
to
app.use( bodyParser.json() );
I have no idea why, but I can't force Angular working here. Does anybody have ideas of why this may be?
I can't even make a simple input form with binded model. There are always just {{model}} and this
File tree
/app.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/client'));
app.use(bodyParser.json());
require('./app/routes.js')(app);
app.listen(port, () => {
console.log('Server listening on port 3000...');
});
/app/routes.js
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/mes.db');
var _ = require('underscore');
module.exports = function (app) {
app.get('/messages', (req, res, next) => {
try {
var messages = [];
// Some db stuff
res.json(messages);
} catch (err) {
next(err);
}
});
app.set('views', './views');
app.set('view engine', 'pug');
app.get('*', (req, res) => {
res.render('index');
});
};
/client/controller.js
angular.module('myViewerController', [])
.controller('mainController', ['$scope','$http','Messages', function($scope, $http, Messages) {
$scope.formData = {};
$scope.loading = true;
Messages.get()
.success(function(data) {
$scope.messages = data;
$scope.loading = false;
})
.error(data => {
console.log('Error: ' + data);
});
}]);
/client/core.js
angular.module('myViewer', ['myViewerController', 'myViewerService']);
/client/service.js
angular.module('myViewerService', [])
.factory('Messages', ['$http', function ($http) {
return {
get: function () {
return $http.get('/messages');
}
}
}]);
/views/layout.pug
doctype html
html(ng-app='myViewer')
head
meta(charset='utf-8')
link(href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', rel='stylesheet')
body(ng-controller='mainController')
block content
block scripts
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js')
script(src='../client/controller.js')
script(src='../client/service.js')
script(src='../client/core.js')
/views/index.pug
extends layout
block content
.container(ng-controller='mainController')
.row
table.table-bordered
thead
tr
th Id
th Caller
th Message
th Date
tbody(ng-repeat='m in messages')
tr
td {{m.id}}
td {{m.caller}}
td {{m.text}}
td {{m.date}}
Thanks Muli Yulzary.
I've just changed
in
/app/routes.js
var path = require('path');
// ..
app.get('/', (req, res) => {
res.render('index', {root: path.join(__dirname, '../client')});
});
and in
/views/layout.pug
script(src='./controller.js')
script(src='./service.js')
script(src='./core.js')
I am learning node and express to create an api for an angular app I will be creating.
When I try and post something the req.body seems to be blank.
This is my server.js file
'use strict';
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
router = require('./api'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/my_db');
app.use(bodyParser.json());
app.use('/api', router);
app.get('/', function(req, res) {
res.render(__dirname + '/index.jade');
});
app.listen(3001, function() {
console.log('Listening on port 3001');
});
and this is my api/index.js file:
'use strict';
var express = require('express'),
Todo = require('../models/todo'),
router = express.Router();
router.get('/todos', function(req, res) {
Todo.find({}, function(err, todos) {
if(err) {
return console.log(err);
}
res.json({todos: todos});
});
});
router.post('/todos', function(req, res) {
var todo = req.body;
res.json({todo: todo});
});
module.exports = router;
when I use postman to post this to http://localhost:3001/api/todos:
{
'name': 'Walk the Dog',
'completed': false
}
my response is:
{
"todo": {}
}
I can't see why this would be blank, any help is appreciated.
UPDATE
Turns out I was posting text in postman instead of JSON.
use this in your server.js file
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());