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

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

Related

How to get req.body MEAN-Stack

I use the MEAN-Stack to upload images with tags.
While posting is working for me I cant get the form data for my updating/put part. I'm stuck at this part here in my routes file:
router.put('/update/:uuid/:filename', upload.single(), function (req, res, next) {
// console.log("_______________________req.FILES_______________________________________");
// console.log(req.files);
// console.log("_______________________req_______________________________________");
// console.log(req);
console.log("_______________________req.BODY_______________________________________");
console.log(req.body);
console.log(req.user);
Upload.findOneAndUpdate({
'file.filename': req.params.uuid,
'file.originalname': req.params.filename
}, {
// $set: {
// tags: req.body.tags
// }
},
function (err, upload) {
if (err) next(err);
else {
res.send(upload);
}
});
});
I I get something like this in the console.
_______________________req.BODY_______________________________________
{ '0': { _id: '593bff833ffbe41a523d03ad',
name: 'asdasdasd',
tags: { info: 'TestTag, Bla' },
created: '2017-06-10T14:17:39.501Z',
file:
{ fieldname: 'file',
originalname: 'ZzpXc6c.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '6fca88b03e88b7e72a751d7a44e9ed04',
path: 'uploads/6fca88b03e88b7e72a751d7a44e9ed04',
size: '303915' },
__v: '0',
'$hashKey': 'object:4' } }
This is the form
<div ng-controller="formCtrlUpdate" id="example-form" action="#">
<h2>Update</h2>
<ul>
<li ng-repeat="upload in image">
<a ng-href='{{upload.file.path + "/" + upload.file.originalname}}'>{{upload.file.originalname}}</a></br>
<img ng-src='{{upload.file.path + "/" + upload.file.originalname}}' />
<form ng-submit="submit()">
<legend>Update file here:</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name" ng-model="upload.name" />
<br/>
<label for="CreatorArtist">Artist:</label>
<input type="text" name="CreatorArtist" id="CreatorArtist" class="demo-default" ng-model="upload.tags.CreatorArtist" />
<br/>
<label for="info">Image Description:</label>
<input type="text" name="info" id="info" ng-model="upload.tags.info" />
<br/>
<input type="submit" value="Update" />
</form>
</li>
</ul>
</div>
FYI this ist the working Uploading part
Routes
router.post('/', upload.single('file'), function (req, res, next) {
console.log(req.body);
var newUpload = {
name: req.body.name,
tags: req.body.tags,
created: Date.now(),
file: req.file
};
Upload.create(newUpload, function (err, next) {
if (err) {
next(err);
} else {
res.send(newUpload);
}
});
});
Upload Form
<div ng-controller="formCtrl">
<h2>Upload</h2>
<h1>Ein Test Upload</h1>
<form ng-submit="submit()">
<legend>Upload a new file here:</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name" ng-model="upload.name" required/>
<br/>
<label for="CreatorArtist">Artist:</label>
<input type="text" name="CreatorArtist" id="CreatorArtist" class="demo-default" ng-model="upload.tags.CreatorArtist" required/>
<br/>
<label for="info">Image Description:</label>
<input type="text" name="info" id="info" ng-model="upload.tags.info" required/>
<br/>
<label for="file">File:</label>
<input type="file" class="imgInp" name="file" id="file" ng-model="upload.file" ngf-select ngf-max-size="25MB" required/>
<br/>
<input type="submit" value="Submit" />
</form>
</div>
and the controller
var app = angular.module('fileUpload', [
'ngFileUpload',
'ngResource',
'ngRoute'
]);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$routeProvider.
when('/', {
templateUrl: '../views/home.html'
}).
when('/uploadForm', {
templateUrl: '../views/uploadForm.html'
}).
when('/updateForm', {
templateUrl: '../views/updateForm.html'
}).
otherwise('/');
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
$scope.submit = function () {
// console.log($scope.upload)
Upload.upload({
url: '/uploads',
method: 'post',
data: $scope.upload
}).then(function (response) {
console.log(response.data);
$scope.all.push(response.data);
$scope.upload = {};
console.log("Uploaded")
})
}
}]);
app.controller('formCtrlUpdate', ['$http', 'Upload', '$scope', '$routeParams', function ($http, Upload, $scope, $routeParams) {
console.log($routeParams);
$http.get('/uploads/update/' + $routeParams.uuid + '/' + $routeParams.filename).then(function (response) {
console.log(response.data);
$scope.image = response.data;
console.log("Beginning");
});
$scope.submit = function () {
console.log($scope.image)
// console.log("Update")
Upload.upload({
url: '/uploads/update/' + $routeParams.uuid + '/' + $routeParams.filename,
method: 'put',
// data: {
// _method: 'PUT',
// data: $scope.image
// }
data: $scope.image
}).then(function (response) {
// console.log(response.data);
$scope.all.push(response.data);
// $scope.image = {};
console.log("Update")
})
}
}]);
My question is now how can I get the form data in my req.body? Something like req.body.0 is not possible. With which parameters I can access something like in my POST/Upload part?
You can get the form data using req.body[0] It will display all the form data which you passed when you click update button .
Result:
{ _id: '593bff833ffbe41a523d03ad',
name: 'asdasdasd',
tags: { info: 'TestTag, Bla' },
created: '2017-06-10T14:17:39.501Z',
file:
{ fieldname: 'file',
originalname: 'ZzpXc6c.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '6fca88b03e88b7e72a751d7a44e9ed04',
path: 'uploads/6fca88b03e88b7e72a751d7a44e9ed04',
size: '303915' },
__v: '0',
'$hashKey': 'object:4'
}
or
if you want to get specific field like name you can use req.body[0].name

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

AngularJS dindn't work in firefox

I wrote a login for a web-application. In chrome the login works but not in firefox.
<form ng-submit="$ctrl.login()">
<div class="cClearFloat">
<input type="text" name="Benutzername" placeholder="Benutzername" ng-model="$ctrl.userName">
</div>
<div class="cClearFloat">
<input type="password" name="Passwort" placeholder="Passwort" ng-model="$ctrl.password">
</div>
<div class="cClearFloat">
<div class="cButtonLogin" class="button">
<button class="cLinkLogin" type="submit">Anmelden</button>
</div>
</div>
</form>
login call:
login() {
this.userService.login(this.userName, this.password);
}
login:
login(userName, password) {
this.$http.post("http://localhost:20670/login", { UserName: userName, Password: password }).then((response) => {
this.userInfo = this.hateoasService.fromData(response.data);
this.$http.defaults.headers.common.LoginToken = this.userInfo.LoginToken;
this.isLoggedIn = true;
}, (response) => {
swal({
title: response.data.error,
type: 'error'
})
});
}
All what happens when I test it in firefox is that it reloads the page. Does someone know why it's not working? Is it possible that it makes the reload is because angularjs isn't available and he takes the default from ng-submit?
in my console I had this error
Use ng-submit on your form and change the button type to submit
On your view:
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="login()">
<input type="text" name="Benutzername" placeholder="Benutzername" ng-model="model.userName">
<input type="password" name="Passwort" placeholder="Passwort" ng-model="model.password">
<button class="cLinkLogin" type="submit">Anmelden</button>
</form>
</div>
On controller :
var app = angular.module("myApp", []);
app.controller("myCtrl", myCtrl);
function myCtrl($scope) {
$scope.model = {};
$scope.login = function() {
alert("username: " + $scope.model.userName + ", password: " + $scope.model.password);
}
}
See http://codepen.io/anon/pen/dNgvJp?editors=1010

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.

Angular js:Not able to get the response for the rest method

I am trying to create a simple login form using angular js and rest webservice.
I am able to call the rest webservice, but not able to get the response.
1)Login form:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<div class="alert alert-danger">Error</div>
<form name="form" role="form" method="post" data-ng-submit="login(credentials)"
data-ng-controller="LoginController">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" data-ng-model="credentials.username" required />
<span class="help-block">Username is required</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" data-ng-model="credentials.password" required />
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Login</button>
<img src="img/ajax-loader-blue.gif" />
Register
</div>
</form>
</div>
2)Restwebservice
#Path("/login")
public class LoginRestfulService {
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Users getUserProfile(CredentialInBean credentials) {
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+" credentials: "+credentials.getUsername()+""+credentials.getPassword());
UserService userService = new UserService();
return userService.getUserProfile(credentials);
}
}
3)
public Users getUserProfile(CredentialInBean credentials) {
if(credentials!=null && credentials.getUsername().equals("Firstname")){
Users user = new Users();
user.setFirstName("Firstname");
user.setLastName("lastname");
return user;
}
return null;
}
4)LoginController
app.controller('LoginController', function($scope, $rootScope, AUTH_EVENTS,
AuthService) {
$scope.credentials = {
username : '',
password : ''
};
$scope.login = function(credentials) {
AuthService.login(credentials).then(function(user) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.currentUser = null;
$scope.setCurrentUser = function(user) {
$scope.currentUser = user;
};
}, function() {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
})
5)AuthService
services.factory('AuthService', function($http, Session) {
var authService = {};
var response='';
authService.login = function(credentials) {
return $http.post('/aclf/rest/login', credentials).then(function(response) {
if (response !== null) {
response = { success: true };
} else {
response = { success: false, message: 'Username or password is incorrect' };
}
alert(response.data);
return response.data;
});
};
});
Here respose.data comes as undefined.
Can any one help me to solve the issue?
you can't override the response here.
For the best you can add more attributes to this object like:
services.factory('AuthService', function($http, Session) {
var authService = {};
var response='';
authService.login = function(credentials) {
return $http.post('/aclf/rest/login', credentials).then(function(response) {
if (response !== null) {
response.success = true ;
} else {
response = {};
response.success = false;
response.message = 'Username or password is incorrect';
}
alert(response.data);//you will preserve the data
return response.data;//won't be undefined
});
};
});

Resources