Cannot POST /api/ - angularjs

I am trying to get an Object file to be sent to server using AngularJS and mongoose module for NodeJS. I do get the Object but it doesn't get sent to the server because of Cannot POST /api/appointment/new error.
Here is my HTML file:
<div class="row">
<div class="col-sm6 col-sm-offset-3">
<div class="row">
<strong>Date:</strong>
<label>
<input type="text" type="date" ng-model="new.date" class="form-control">
</label>
<strong>Name Surname:</strong>
<label>
<input type="text" ng-model="new.nameSurname" class="form-control">
</label>
</div>
<div class="row">
<strong>Case:</strong>
<label>
<input type="text" ng-model="new.description" class="form-control">
</label>
<strong>Contact number:</strong>
<label>
<input type="tel" ng-model="new.contactNumber" class="form-control">
</label>
<button ng-click='createAppointment()'>Create appointment!</button>
</div>
</div>
</div>
My server.js file:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var newAppointment = require('./server/controllers/newAppointment.js');
mongoose.connect('mongodb://localhost:27017/dental');
app.use(bodyParser.json());
//noinspection JSUnresolvedVariable
app.use('/app', express.static(__dirname + '/app'));
//noinspection JSUnresolvedVariable
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.get('/', function(req, res){
res.sendfile('index.html');
});
//New appointment function
app.post('api/appointment/new', newAppointment.create);
app.listen('3000', function() {
console.log("Listening on :3000")
});
Server controller:
var mongoose;
mongoose = require('mongoose');
var appointment;
appointment = require('../datasets/appointment.js');
module.exports.create = function(req, response) {
console.log(req.body)
};
App controller:
(function() {
//noinspection JSUnresolvedFunction
angular.module('dentalAdviser')
.controller('appointmentController', ['$scope', '$state', '$http', function ($scope, $state, $http) {
$scope.createAppointment = (function() {
console.log($scope.new);
$http.post('api/appointment/new', $scope.new).success(function (response) {
}).error(function (error) {
console.log(error);
})
});
}])
}());
And dataset for Object:
var mongoose = require('mongoose');
module.export = mongoose.model('appointment', {
nameSurname: String,
date: String,
description: String,
contactNumber: String
});

This:
app.post('api/appointment/new', newAppointment.create);
should probably be:
app.post('/api/appointment/new', newAppointment.create);

Related

Why am I getting a 404 error when using ngresource save?

I'm following an old Pluralsight tutorial that is no longer updated and have hit a wall: I am using Visual Studio 2013 and Angular JS v1.4, and have to use this tutorial as we are using this version of AngularJS at work.
HTML TEMLPLATE: NewEvent.html
<div style="padding-left:20px; padding-right: 20px">
<div class="container">
<h1>New Event</h1>
<hr />
<form name="newEventForm">
<fieldset>
<label for="eventName">Event Name:</label>
<input id="eventName" type="text" required ng-model="event.name" placeholder="Name of your event..." />
<label for="eventDate">Event Date:</label>
<input id="eventDate" type="text" required ng-pattern="/\d\d/\d\d/\d\d\d\d/" ng-model="event.date" placeholder="format (mm/dd/yyyy)..." />
<label for="eventTime">Event Time:</label>
<input id="eventTime" type="text" required ng-model="event.time" placeholder="Start and end time..." />
<label for="eventLocation">Event Location:</label>
<input id="eventLocation" type="text" required ng-model="event.location.address" placeholder="Address of event..." />
<br />
<input id="eventCity" type="text" required ng-model="event.location.city" class="input-small" placeholder="City..." />
<input id="eventProvince" type="text" ng-model="event.location.province" class="input-small" placeholder="Province..." />
<div>{{event.name}}</div>
<label for="eventImageUrl">Image:</label>
<input id="eventImageUrl" type="url" ng-model="event.imageUrl" class="input-xlarge" placeholder="Url of image..." />
</fieldset>
<img ng-src="{{event.imageUrl}}" src="" />
<br />
<br />
<button type="submit" ng-disabled="newEventForm.$invalid" ng-click="saveEvent(event, newEventForm)" class="btn btn-primary">Save</button>
<button type="button" ng-click="cancelEdit()" class="btn btn-default">Cancel</button>
</form>
</div>
CONTROLLER: EditEventController.js
'use strict'
eventsApp.controller('EditEventController',
function EditEventController($scope, eventData) {
$scope.event = {};
$scope.saveEvent = function (event, newEventForm) {
if (newEventForm.$valid) {
eventData.save(event)
.$promise
.then(function (response) { console.log('success', response) })
.catch(function (response) { console.log('failure', response) });
}
};
$scope.cancelEdit = function () {
window.location = "./EventDetails.html";
}
});
SERVICE: EventData.js
eventsApp.factory('eventData', function ($resource) {
var resource = $resource('data/event/:id.json', { id: '#id' }, { "getAll": { method: "GET", isArray: true, params: { something: "foo" } } });
return {
getEvent: function () {
return resource.get({ id: 1 });
},
save: function (event) {
event.id = 999;
return resource.save(event);
}
}
});
I had to specify '.json' in the var resource line and that's the only change I made to the code given by the tutors, because another page (which uses the getEvent function in the service) wouldn't work unless I did that.
When I click save, I get the 'failure' response in the console even though the model for the event has built correctly.
Screenshot of error in console:-
File structure:-
The 404 error appears to be attached to the save destination, even though as far as I can tell the URL is correct. How do I correctly use ngresource.save to save this file?
web-server.js - check get & post path
const express = require('express');
const path = require('path');
const events = require('./eventsController');
const app = express();
const rootPath = path.normalize(__dirname + '/../');
const bodyParser = require('body-parser');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(rootPath + '/app'));
app.get('/data/event/:id', events.get);
app.post('/data/event/:id', events.save);
app.listen(port, function () {
console.log('Listening on port ' + port + '...');
});
EventData.js - check at the resource path
'use strict';
eventsApp.factory('eventData', function ($resource) {
var resource = $resource('/data/event/:id', { id: '#id' });
return {
getEvent: function () {
return resource.get({ id: 2 });
},
save: function (event) {
event.id = 999;
return resource.save(event);
}
};
});

How to pass data-plugin="timepicker" value to controller in angularJS

I have code to pass date and time to controller.
Here is HTML code,
<div class="page-content" ng-app="app">
<div ng-controller="postAppoinmentCtr as ctrl" class="panel-body">
<form ng-submit="submitForm()" id="form1">
<input name="time" ng-model="time" type="text" class="form-control" ng-model="time" data-plugin="timepicker" autocomplete="off"/>
<input name="date" ng-model="date" type="text" class="form-control" data-plugin="datepicker"/>
<input..ng-model="type"...></input>
<input..ng-model="Description"...></input>
<button ...>
</form>
</div>
</div>
Here is angular js part
var app = angular.module('app', []);
app.controller('postAppoinmentCtr', function($scope, $http, $location) {
$scope.submitForm = function(){
var url = $location.absUrl() + "/addAppoinment";
alert(url);
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
var data = {
type: $scope.type,
date: $scope.date,
time: $scope.time,
description: $scope.description
};
$http.post(url, data, config).then(function (response) {
$scope.postResultMessage = "Sucessful!";
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.type = "";
$scope.date = "";
$scope.time ="";
$scope.description ="";
}
});
When click the button type and description pass to controller. But date and time not. I can do this using
<input id="date-birth" class="form-control" type="date" ng-model="date">
this line. But I need to use data-plugin="datepicker" .
I'm new one for the angularjs and I try to many ways for solve this problem.
Please give me some answer this. Thanks in advance.

how to select values from mongodb using mongoose

i am using meanstack now i try to fetch the data from mongodb with the help of angularjs i am very new in this technology.i insert the values correctly now i want to retrieve from mongodb-mongoose
i am using meanstack now i try to fetch the data from mongodb with the help of angularjs i am very new in this technology.i insert the values correctly now i want to retrieve from mongodb-mongoose
var app = angular.module("App", [ ]);
app.controller('MongooseController', ['$scope', '$http' ,'$window', '$filter',
function ($scope, $http, $window, $filter) {
debugger;
var refresh = function () {
$http.get('/ViewUser').then(function (response) {
$scope.ViewUsers = response.data;
});
};
refresh();
$scope.AddNewDetails = function ( ) {
$http.post('/AddNewDetails', $scope.user).then(function (response) {
});
};
}]);
server
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/crud');
var Schema = new mongoose.Schema({
email: String,
name: String,
age: Number,
date: { type: Date, default: Date.now }
});
var user = mongoose.model('emps', Schema);
app.get('/ViewUser', function (req, res) {
user.find({}, function (err, docs) {
console.log(docs);
});
});
app.post('/AddNewDetails', function (req, res) {
new user({
email: req.body.email,
name: req.body.name,
age: req.body.age
}).save(function (err, doc) {
if (err) {
res.json(err);
}
else {
res.send('Successfully inserted!');
}
});
});
app.listen(8082);
console.log("server running on port 8082");
<!DOCTYPE html>
<html ng-app="App">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="Controller/MongooseCrud.js"></script>
</head>
<body >
<div ng-controller="MongooseController">
<label for="email">Email: </label>
<input type="email" name="email" ng-model="user.email" /><br />
<label for="name">Name: </label>
<input type="text" name="name" ng-model="user.name" /><br />
<label for="age">Age: </label>
<input type="number" name="age" ng-model="user.age"/><br />
<input type="Button" value="submit" ng-click="AddNewDetails()">
<ul ng-repeat="ViewUser in ViewUsers">
<li>{{ViewUser.name}}</li>
</ul>
</div>
</body>
</html>
It should be,
User.find({}, function(err, docs) {
console.log(docs);
}
Also change your request as,
$http.get('/ViewUser').then(function (response) {
$scope.ViewUsers = response.data;
});

Image upload and retrieve using Node Express 4 MongoDB

I have created a simple login and signup using MEAN stack languages. I have a profile page where user can edit his info like name, address, etc. I am able to store and retrieve input type "text" fields. How can i add image upload feature and retrieve uploaded images? Im new to mean stack so can anyone please help me? Thanks.
My server.js is this
require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
// use JWT auth to secure the api
app.use('/api', expressJwt({ secret: config.secret }).unless({ path: ['/api/users/authenticate', '/api/users/register'] }));
// routes
app.use('/login', require('./controllers/login.controller'));
app.use('/register', require('./controllers/register.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/api/users', require('./controllers/api/users.controller'));
// make '/app' default route
app.get('/', function (req, res) {
return res.redirect('/app');
});
// start server
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
HTML to save and view saved data looks like this
<h1>My Account</h1>
<div class="form-container">
<form method="post" >
<div class="form-group">
<label for="firstName">First name</label>
<input type="text" id="firstName" class="form-control" ng-model="vm.user.firstName" required />
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<input type="text" id="lastName" class="form-control" ng-model="vm.user.lastName" required />
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" class="form-control" ng-model="vm.user.username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" ng-model="vm.user.password" />
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" id="password" class="form-control" ng-model="vm.user.address" />
</div>
<div class="form-group">
<button class="btn btn-primary" ng-click="vm.saveUser()">Save</button>
<button class="btn btn-danger" ng-click="vm.deleteUser()">Delete</button>
</div>
</form>
</div>
<!-- View Data -->
<div class="col-md-12">
<h1>Hi {{vm.user.firstName}}!!</h1>
<p><strong>User Name :</strong> {{vm.user.username}} </p>
<p><strong>Full Name : </strong> {{vm.user.firstName}} {{ vm.user.lastName}}</p>
<p><strong> Your address is : </strong> {{vm.user.address}}</p>
</div>
and app.js looks like this
(function () {
'use strict';
angular
.module('app')
.controller('Account.IndexController', Controller);
function Controller($window, UserService, FlashService) {
var vm = this;
vm.user = null;
vm.saveUser = saveUser;
vm.deleteUser = deleteUser;
initController();
function initController() {
// get current user
UserService.GetCurrent().then(function (user) {
vm.user = user;
});
}
function saveUser() {
UserService.Update(vm.user)
.then(function () {
FlashService.Success('User updated');
})
.catch(function (error) {
FlashService.Error(error);
});
}
function deleteUser() {
UserService.Delete(vm.user._id)
.then(function () {
// log user out
$window.location = '/login';
})
.catch(function (error) {
FlashService.Error(error);
});
}
}
})();
and user.service.js which is used to update data to db is
function updateUser() {
// fields to update
var set = {
firstName: userParam.firstName,
lastName: userParam.lastName,
username: userParam.username,
address: userParam.address,
};
// update password if it was entered
if (userParam.password) {
set.hash = bcrypt.hashSync(userParam.password, 10);
}
db.users.update(
{ _id: mongo.helper.toObjectID(_id) },
{ $set: set },
function (err, doc) {
if (err) deferred.reject(err.name + ': ' + err.message);
deferred.resolve();
});
}
To build the image upload feature, You need to add functionality to both the frontend and backend.
You need to have a custom image upload directive or component in the angularjs and Some kind of upload handler package in the Express Server as well.
Keeping all this in mind, Google will surely lead you to best package available for you.
One code sample can be found here : https://gist.github.com/keithics/bf0e13feaee5631fa936b7b203029cd4
Other: https://github.com/nervgh/angular-file-upload
There are huge number of libraries available for the same.

Angularjs list not refreshing on form submit using MEAN

Some what new to the MEAN stack. Currently I'm reworking an small app I did through codeschool to be full MEAN stack.
The app created can be seen here
Code School app
In rewriting the app using the MEAN stack after submitting the form I must refresh the page to see the city added to the list. What do I need to fix so I don't need to refresh the page for the new Item to be added to the list?
If I'm missing any relevant code below here is my git hub link
git hub link
Here is my code:
angular.module('Cityapp').controller('CityIndexController', function(City, $scope){
$scope.cities = City.query();
window.sc = $scope;
});
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
console.log($scope.city);
console.log(data);
console.log($scope.city);
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
<form ng-controller="CityCreateController">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="saveCity(city)"/>
</form>
<ul ng-controller="CityIndexController" class="city-list">
<li ng-repeat="city in cities">
<a href="#">
{{city.city}}</a></li>
</ul>
It should looks something like that
;(function() {
function Cities($http) {
function City() {
}
City.prototype.save = function() {
return $http.post('/api/city', this);
};
City.cities = [];
City.add = function(city) {
city.save().then(function() {
City.cities.push(city);
});
};
City.getAll = function() {
$http.get('/api/cities').then(function(response) {
City.cities = response.data.map(function(data) {
return new City(data);
});
return cities;
});
};
return City;
}
function CityCreateController(Cities) {
var mv = this;
mv.city = new Cities();
mv.saveCity = function() {
Cities.add(mv.city);
};
}
function CityIndexController($scope, Cities) {
var mv = this;
$scope.$watchCollection(function() {
return Cities.cities;
}, function(cities) {
mv.cities = cities || [];
});
Cities.getAll();
}
angular
.module('app', [])
.factory('Cities', ['$http', Cities])
.controller('CityCreateController', ['Cities', CityCreateController])
.controller('CityIndexController', ['$scope', 'Cities', CityIndexController]);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<form ng-controller="CityCreateController as mv">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="mv.city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="mv.city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="mv.saveCity()"/>
</form>
<ul ng-controller="CityIndexController as mv" class="city-list">
<li ng-repeat="city in mv.cities">
<a href="#">
{{city.city}}</a></li>
</ul>
</body>
</html>
Found a simple fix
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.cities = City.query();
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
Just added the
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
to the .success. Works like it should. Now on to my next issue.

Resources