AngularJS lost data from multipartForm directive to routes - javascript

I am trying to build an Excel file uploader and parse the data in the routes to store it but it appears the data is lost in translation from the FormData sent in through the $http service route. I have no clue what to do! If you have any experience with this please help!
Html View:
<form ng-controller="myCtrl">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" ng-model="myFile.name">
</div>
<div class="form-group" >
<input type="file" file-model="myFile.file"/>
</div>
<button ng-click="Submit()">upload me</button>
</form>
Controller View:
myApp.controller('myCtrl', ['$scope', 'multipartForm', function($scope, multipartForm){
$scope.myFile = {};
$scope.Submit = function(){
var uploadUrl = '/upload';
multipartForm.post(uploadUrl, $scope.myFile);
}
}]);
Service View:
myApp.service('multipartForm', ['$http', function($http){
this.post = function(uploadUrl, data){
var fd = new FormData();
for(var key in data) {
fd.append(key, data[key]);
}
$http.post(uploadUrl, fd, {
transformRequest: angular.indentity,
headers: { 'Content-Type': undefined }
});
}
}])
Directive View:
myApp.directive('fileModel', ['$parse', function($parse){
return {
restrict: 'A',
link: function(scope, element, attrs){
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
})
})
}
}
}])
This is the route view where the data does not travel through.
module.exports = function (app) {
app
.post('/upload', function(req, res){
console.log(req.body);
console.log(req.files);
});
}
Server.js
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer({ dest: './uploads/'});
var app = express();
// if using body-parser
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
// if mongoose, require mongoose
//require('./server/config/mongoose.js');
//routes
require('./server/config/routes.js')(app);
app.listen(8000, function () {
console.log('listening on port 8000');
})

the simple way is to use ng-file-upload. it's the most popular AngularJS directive for file upload using HTML5 with FileAPI polyfill for unsupported browsers.
Docs
Demo

Related

Cannot post data from Angular.js to Node.js

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);
});

What is wrong with my POST, resulting in an empty req.body

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() );

Angular-BrowerSync-Express Cannot POST from client-side Express back-end route

I'm working with an Angular-Gulp-Browsersync-Express app and I'm having trouble getting angular's $http resource to POST a simple "contact us" form to my express server.
Every time I try to submit my form I get the following error:
POST http://localhost:8080/submitContactUsForm 404 (Not Found)
Cannot POST /submitContactUsForm
To be up front, I've got much more experience working with the front-end than I do with the back-end so it could very well be that I've got the wrong server setup.
Here is my Express Server:
'use strict';
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var http = require('http');
var routes = require('.././src/index.module.js');
// var contactController = require('.././api/http/controllers/contactcontroller.js');
// require database data modeling via mongoose
var mongoose = require('mongoose');
// Express Session allows us to use Cookies to keep track of
// a user across multiple pages. We also need to be able to load
// those cookies using the cookie parser
var session = require('express-session');
var cookieParser = require('cookie-parser');
// Flash allows us to store quick one-time-use messages
// between views that are removed once they are used.
// Useful for error messages.
var flash = require('connect-flash');
// Use express and set it up
var app = express();
app.use(cors());
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/submitContactUsForm', function(req, res) {
console.log('it hit the server');
})
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync').create();
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init({
startPath: '/',
cors: true,
browser: browser,
port: 8080,
server: {
baseDir: baseDir,
routes: routes,
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
next();
}
},
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['setenvconstants','watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['setenvconstants','build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
Here is the Angular Controller I am trying to post from:
(function() {
'use strict';
angular
.module('commonSenseDietApp')
.controller('ContactController', ContactController);
function ContactController($http, $log) {
// controllerAs syntax
var vm = this;
vm.contactInfo = {
email: vm.email
}
vm.processContactForm = function() {
return $http.post('/submitContactUsForm', vm.contactInfo)
.then(returnSendSuccessful)
.catch(sendFail);
function returnSendSuccessful(response) {
$log.log(response.data);
return response.data;
}
function sendFail(err) {
return $log.error(err.data);
}
}
}
})();
Here are my Client-Side Routes:
(function() {
'use strict';
angular
.module('commonSenseDietApp')
.config(routeConfig);
function routeConfig($routeProvider) {
// Home Page
$routeProvider
.when('/', {
templateUrl: 'app/views/pages/home.html',
controller: 'MainController',
controllerAs: 'vm'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// About Page
$routeProvider
.when('/about', {
templateUrl: 'app/views/static/about.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Terms of Use Page
$routeProvider
.when('/terms-of-use', {
templateUrl: 'app/views/static/terms-of-use.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Privacy Policy Page
$routeProvider
.when('/privacy-policy', {
templateUrl: 'app/views/static/privacy-policy.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Contact Us Page
$routeProvider
.when('/contact', {
templateUrl: 'app/views/pages/contact.html',
controller: 'ContactController',
controllerAs: 'vm'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Answer Page
$routeProvider
.when('/answer', {
templateUrl: 'app/views/pages/answer.html',
controller: 'AnswerController',
controllerAs: 'vm'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// How It Works Page
$routeProvider
.when('/how-it-works', {
templateUrl: 'app/views/static/how-it-works.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Algorithm Explainer Page
$routeProvider
.when('/meet-ONNA', {
templateUrl: 'app/views/static/meet-ONNA.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
}
})();
Here is my contact form markup:
<section>
<div class="contact-us-title">
<h1>Contact Us</h1>
</div>
<form class="contact-us-form" name="contactUsForm" ng-submit="vm.processContactForm()">
<div class="form-group">
<input placeholder="name" type="text" name="name" ng-model="vm.name" class="form-control" required />
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.name.$error.required">Required!</span>
</div>
<div class="form-group">
<input placeholder="Email" type="email" name="email" ng-model="vm.email" class="form-control" required />
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.email.$error.required">Required!</span>
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.$error.email">Invalid email!</span>
</div>
<div class="form-group">
<input name="headline" placeholder="Headline" type="text" ng-model="vm.headline" class="form-control" required/>
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.headline.$error.required">Required!</span>
</div>
<div class="form-group">
<textarea name="message" placeholder="Message" type="textbox" ng-model="vm.message" class="form-control" required></textarea>
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.subjectList.$error.required">Required!</span>
</div>
<input type="submit" id="submit-contact-form-btn">
</form>
</section>
I'm also not seeing anything logging to console in the terminal. Any insight on this would be super helpful and very appreciated.
Eureka I found the answer!
Turns out my lack of experience with express playing nice with browersync was certainly a hinderance for me here. The answer lied in Proxying browsersync to express and the use of gulp-nodemon package. After some restructuring I've got the right setup:
My Browser-Sync server and gulp init tasks:
'use strict';
var path = require('path');
var port = process.env.PORT || 8080;
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync').create();
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
var nodemon = require('gulp-nodemon');
var reload = browserSync.reload;
function browserSyncInit(baseDir, browser) {
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init({
startPath: '/',
cors: true,
browser: browser = browser === undefined ? 'default' : browser,
proxy: 'http://localhost:8081',
port: port
// https: true
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]' // Only needed for angular apps
}));
// Run Gulp tasks
gulp.task('serve', ['browser-sync','setenvconstants','watch']);
gulp.task('browser-sync', ['nodemon'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['setenvconstants','build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
gulp.task('nodemon', [], function(done) {
var running = false;
return nodemon({
script: 'api/app.js',
watch: ['api/**/*.*', 'src/**/*.*']
})
.on('start',function() {
if (!running) {
done();
}
running = true;
})
.on('restart', function() {
setTimeout(function(){
reload();
}, 500);
});
});
My Express server:
var express = require('express');
var bodyParser = require('body-parser');
var http = require('http');
var port = process.env.PORT || 8081;
var cors = require('cors');
var path = require('path');
var publicRoutes = require('./http/routes/web.js');
// require database data modeling via mongoose
var mongoose = require('mongoose');
// Express Session allows us to use Cookies to keep track of
// a user across multiple pages. We also need to be able to load
// those cookies using the cookie parser
var session = require('express-session');
var cookieParser = require('cookie-parser');
// Flash allows us to store quick one-time-use messages
// between views that are removed once they are used.
// Useful for error messages.
var flash = require('connect-flash');
// Use Express and set it up
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
// Parse requests to JSON
app.use(bodyParser.json({type: '*/*', limit: '50mb'}));
// set Jade as the view engine
app.set('view engine', 'jade');
// tell server where to find our views
app.set('views', __dirname + '/.././src/app/views');
// make sure bower components are installed.
app.use('/underscore', express.static(path.resolve('.././node_modules/underscore')));
// tell our server where to find static assets depending on the environment.
process.env.NODE_ENV == 'production' ? app.use(express.static(path.join(__dirname + '/../..'))) : app.use(express.static(path.join(__dirname + '/.././dist')));
// enable cors
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": ["Origin, X-Requested-With, Content-Type, Accept, Authorization"],
"preflightContinue": false
}));
// Pull in our public routes
app.use('/api', publicRoutes);
// Listen
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info("==> 🌎 Listening on port %s. Visit http://localhost:%s/ in your browser.", port, port);
}
});
I'm now able to $http.post from my Angular controller considering the route prefix in my express server:
vm.processContactForm = function() {
return $http.post('/api/submitContactUsForm', vm.contactInfo)
.then(returnSendSuccessful)
.catch(sendFail);
function returnSendSuccessful(response) {
$log.log(response);
// return response.data;
}
function sendFail(err) {
return $log.error(err.data);
}
}
The only issue I'm having now is with...
process.env.NODE_ENV == 'production' ? app.use(express.static(path.join(__dirname + '/.././src'))) : app.use(express.static(path.join(__dirname + '/.././dist')));
wherein '/dist' is served just fine but '/src' only serves a blank index.html page to my localhost. I'll post this as a new question and consider this issue solved. Thanks for the help!

App error displaying blank

my app's idea is simple. a user inputs text and then it gets diplayed and saved into the db. The problem am having is that it displays blank. I have a lot of code so am going to put the bare minimum.
my server :
// dependencies
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var hash = require('bcrypt-nodejs');
var path = require('path');
var passport = require('passport');
var localStrategy = require('passport-local' ).Strategy;
var meetupsController = require('./meetups-controller');
// mongoose
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/mean-auth');
// user schema/model
var User = require('./models/user.js');
// create instance of express
var app = express();
// require routes
var routes = require('./routes/api.js');
app.get('/api/meetups', meetupsController.list);
app.post('/api/meetups', meetupsController.create);
// define middleware
app.use(express.static(path.join(__dirname, '../client')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
// configure passport
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// routes
app.use('/user/', routes);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '../client', 'index.html'));
});
// error hndlers
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res) {
res.status(err.status || 500);
res.end(JSON.stringify({
message: err.message,
error: {}
}));
});
app.use(bodyParser());
app.use('/js', express.static(__dirname + '/client/js'));
//REST API
module.exports = app;
my main angular controller
var myApp = angular.module('myApp', ['ngRoute','ngResource']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my html partial
<body>
<div id='main' ng-controller="loginController">
<form ng-Submit="post()">
<input required type="text" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="button" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class='post' ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.created_by}} says {{post.text}} at {{post.created_at}}</p>
</div>
<div ng-controller="logoutController">
<a ng-click='logout()' class="btn btn-default">Logout</a>
</div>
<div ng-controller="logoutController">
<a ng-click='gotoregister()' class="btn btn-default">register</a>
</div>
</div>
</div>
<div ng-controller="meetupsController">
<h1>There are {{meetups.length}} meetups</h1>
<ul>
<li ng-repeat="meetup in meetups">
{{meetup.name}}
</li>
</ul>
<form ng-submit="createMeetup()">
<input type="text" placeholder="Meetup name" ng-model="meetupName"></input>
<button type="submit">Add</button>
</form>
</div>
</body>
please help
I'm not sure what you mean by "displays blank", but there is likely an issue with these lines:
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
If $scope.meetups is assigned results, you may be overwriting that value with $scope.meetups = []. Remember that the $resource will resolve asynchronously, so assignments won't exactly happen in the order they are written. Try removing the $scope.meetups = [] line.

AngularJS + ExpressJS + mongoose: Add delete functionality

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}`);
}

Categories

Resources