Module unrecognised in Angular while using Node & Mongo - javascript

Working on a primitive enough MEAN-stack project.
When I run the application, the data-binding fails as the module which makes the association between my View and Backend(makes the http connection to my DB) never gets instantiated, and goes unrecognised.
Following error message appears in the console
[$injector:modulerr] Failed to instantiate module moviesApp due to:
Error: [$injector:nomod] Module 'moviesApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Error message is fairly understandable. I seem to have incorrectly(or not at all) created the link between the view "MoviesList.html" and the file containing the module I mentioned above (moviesApp), in the file "Movies.js".
Movies.js makes use of a factory. I've checked the general syntax(can't see how incorrect code inside the actual factory would cause the module to go unrecognised). Having written a basic factory before on jsfiddle, i'm confident that the syntax should be fine. https://jsfiddle.net/Sheepy99/4wmd3zd0/ (granted I chained the factory in that example, but it's the same general premise)
Before I post the rest of my code, it's based off of the example contained here: http://www.dotnetcurry.com/nodejs/1032/nodejs-apps-in-visual-studio-mean-stack
Some of my code is different due to differing versions, and some bits being deprecated since the author published the article(also wondering why he consistently uses double double-quotes).
Any ambiguity or loose ends, ask away.
MoviesList.html
<html>
<!--<meta charset="UTF-8">-->
<title>Node-Express Movie List</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!--<link rel="stylesheet" href="/styles/site.css">-->
 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<!--<script src="/scripts/controller.js"></script>
<script src="/scripts/movies.js"></script>-->
<script src="../public/scripts/movies.js"></script>
<script src="../public/scripts/controller.js"></script>
</head>
<body>
<div class="container">
     <!--<div class="text-center" ng-app="moviesApp" ng-controller="MoviesCtrl">-->
<div class="text-center" ng-app="moviesApp" ng-controller="MoviesCtrl">
         <h1>Node-Express Movie List</h1>
         <div class="col-md-12" control-group="">
             <input type="text" style="width: 200px;" ng-model="newMovieText">
             <button id="btnAddTodo" class="btn" style="margin: 2px;" ng-click="addMovie()" ng-disabled="newMovieText">Add Movie</button>
         </div>
 
         <div class="col-md-5" sticky-note="">
             <h3 class="text-center">Released Movies</h3>
             <!--<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" |="" filter:{released:true}"="">-->
<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" filter:{released:true}>
                 <div class="thumbnail">
                     <input type="checkbox" ng-model="movie.watched" ng-change="movieWatched(movie)">
                      
                     <span ng-class="{watchedMovie: movie.watched}">{{movie.name}}</span>
                 </div>
             </div>
         </div>
 
         <div class="col-md-5" sticky-note="">
             <h3 class="text-center">Coming Up...</h3>
             <div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" filter:{released:false}>
                 <div class="thumbnail">
                     {{movie.name}}
                     <br>
                     <br>
                     <input type="button" value="Released!" class="btn btn-success" btn-link="" released-button="" ng-click="movieReleased(movie)" style="">
                 </div>
             </div>
         </div>
     </div>
</div>
</body>
</html>
movies.js
var app = angular.module('moviesApp', []);
 
app.factory('moviesCRUD', function ($http, $q) {
    function getAllMovies() {
        var deferred = $q.defer();
 
        $http.get('/api/movies').then(function (result) {
            deferred.resolve(result.data);
        }, function (error) {
            deferred.reject(error);
        });
 
        return deferred.promise;
    }
 
    function addMovie(newMovie) {
        var deferred = $q.defer();
 
        $http.post('/api/movies', newMovie).then(function (result) {
            deferred.resolve(result.data.movie);
        }, function (error) {
            deferred.reject(error);
        });
 
        return deferred.promise;
    }
 
    function modifyMovie(updatedMovie) {
        var deferred = $q.defer();
 
        $http.put('/api/movies/' + updatedMovie._id, updatedMovie).then(function (data) {
            deferred.resolve(data);
        }, function (error) {
            deferred.reject(error);
        });
 
        return deferred.promise;
    }
 
    return {
        getAllMovies: getAllMovies,
        addMovie: addMovie,
        modifyMovie: modifyMovie
    };
});
mongoOperations.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//http://stackoverflow.com/questions/24908405/mongoose-and-new-schema-returns-referenceerror-schema-is-not-defined
//link recommends use of what's on line 2 as a solution
mongoose.Promise = global.Promise; //not using promises, this line removes a default setting and also gets rid of a warning about promises
mongoose.connect('mongodb://localhost/moviesDb');
var db = mongoose.connection;
//var movieSchema = mongoose.Schema({ *I shouldn't need this because i've declared "require('mongoose')"
var movieSchema = new Schema({
name: String, //doesn't like if I have spaces on each new line, before the use of characters
released: Boolean,
watched: Boolean
});
var MovieModel = mongoose.model('movie', movieSchema);
db.on('error', console.error.bind(console, "connection error"));
db.once('open', function () {
//console.log("moviesDb is open...");  
MovieModel.find().exec(function (error, results) {
if (results.length === 0) {
MovieModel.create({ name: "The Amazing Spider-Man 2", released: true, watched: false });
MovieModel.create({ name: "The Other Woman", released: true, watched: true });
MovieModel.create({ name: "Shaadi ke Side Effects", released: false, watched: false });
MovieModel.create({ name: "Walk of Shame", released: true, watched: false });
MovieModel.create({ name: "Lucky Kabootar", released: false, watched: false });
}
});
});
exports.fetch = function (request, response) {
MovieModel.find().exec(function (err, res) {
if (err) {
response.send(500, { error: err });
}
else {
response.send(res);
}
});
};
exports.add = function (request, response) {
var newMovie = { name: request.body.name, released: false, watched: false };
MovieModel.create(newMovie, function (addError, addedMovie) {
if (addError) {
response.send(500, { error: addError });
}
else {
response.send({ success: true, movie: addedMovie });
}
});
};
exports.modify = function (request, response) {
var movieId = request.params.movieId;
MovieModel.update({ _id: movieId }, { released: request.body.released, watched: request.body.watched }, { multi: false },
function (error, rowsAffected) {
if (error) {
response.send(500, { error: error });
}
else if (rowsAffected == 0) {
response.send(500, { error: "No rows affected" });
}
else {
response.send(200);
}
}
);
};
server.js
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var path = require("path");
 
var port = process.env.port || 1337;
 
var app = express();
//app.use(bodyParser()); //getting deprecated warning in shell when using this specific line
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(bodyParser.json()); used in stackoverflow solution, can see potential benefit, but isn't helping
var mongoOps = require('./server/MongoOperations.js');
 
app.get('/', function (request, response) {
//response.sendfile("views/MoviesList.html");
//response.sendFile("views/MoviesList.html");
response.sendFile("views/MoviesList.html", { "root": __dirname });
});
app.get('/api/list', function (request, response) {
response.send([{ id: 1, name: "charlie" }, { "id": 2, "name": "ward" }]);
//'Hello World!');
});
app.get('/api/movies', mongoOps.fetch);
 
app.post('/api/movies', mongoOps.add);
 
app.put('/api/movies/:movieId', mongoOps.modify);
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port);
controller.js
app.controller('MoviesCtrl', function ($scope, moviesCRUD) {
    $scope.released = { released: true };
    $scope.notReleased = { released: false };
     
    function init() {
        moviesCRUD.getAllMovies().then(function (movies) {
            $scope.movies = movies;
        }, function (error) {
            console.log(error);
        });       
    }
 
    $scope.movieReleased = function (movie) {
 
        moviesCRUD.modifyMovie({ _id: movie._id, name: movie.name, released: true, watched: movie.watched })
                  .then(function (result) {
                      if (result.status === 200) {
                          movie.released = true;
                      }
                  }, function (error) {
                      console.log(error);
                  });       
    };
 
    $scope.movieWatched = function (movie) {
        moviesCRUD.modifyMovie(movie)
                  .then(function (result) {
                      if (result.status === 200) {
                          console.log("Movie updated");
                      }
                  }, function (error) {
                      movie.watched = !movie.watched;
                  });       
    };
 
    $scope.addMovie = function () {
        moviesCRUD.addMovie({ name: $scope.newMovieText }).then(function (newMovie) {
            $scope.movies.push(newMovie);
            $scope.newMovieText = "";
        }, function (error) {
            console.log(error);
        });       
    };
 
    init();
});
Also, much of my html is being rendered as question marks inside diamonds. This has me absolutely puzzled. Just thought i'd put that out there.
As a noobie, any brief general suggestions would be welcomed, as in adjustments to my code for readability, or approach.

I made a few changes to your code to get Angular to "compile" it, but I didn't have the code for the controller so I could not finish setting it up. But if you look at this plunk, you can see my changes.
<html ng-app="moviesApp">
<head>
<!--<meta charset="UTF-8">-->
<title>Node-Express Movie List</title>
<script data-require="angular.js#1.6.1" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!--<link rel="stylesheet" href="/styles/site.css">-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<!--<script src="/scripts/controller.js"></script>
<script src="/scripts/movies.js"></script>-->
<script src="movies.js"></script>
<!--<script src="../public/scripts/controller.js"></script>-->
</head>
You had issues with the placement of the HEAD in the HTML, plus you bootstrapped the application in the first DIV, which I guess it could work, but it is very non-standard. You start your application in a Plunk or Codepen to make it easier on yourself.
Have fun.

Figured it out:
Because I have the following line near the bottom of server.js, my directory automatically starts of public, when specifying directives for external modules(in this case controller.js and movies.js.
Therefore, my directives were incorrect.
As for the strange diamonds I had mentioned at the bottom of my question, it was due to my files being automatically being saved as ASCII when I created them, when they should've been UTF-8.
An annoying and pedantic problem, but i'm sure someone will eventually find some help from this.
app.use(express.static(path.join(__dirname, 'public')));

Related

using elasticsearch.js is no result

I want show elastic search data on web page that using angular js.
however, not bring data from elasticsearch with that message
Is there anything I need to add or fix in my code?
if anyone answers to me I really appreciate
I have attached an execution screen.
thank you.
Execution screen:
enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController"></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'http://localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
"match_all" : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
}).catch(function (err) {
if (err.status === 404) {
alert("error 404" );
} else {
alert("error : " + err );
}
});
});
</script>
</body>
</html>

Mean stack controller server side not connecting to API

I am new to Mean stack and have been struggling with this for quite a few days.
To give you an idea of what I am trying to make; I am creating a tagging tool that stores all requests and their tags in a collection called tags and then also storing all of the distinct tags into the Tagnames collection. I would like to understand why my MEAN stack api layer gives me a 404 error.
This error only occurs with my put method in the server.js file.
TaggingTool\server.js
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
tagsController = require('./server/controllers/tagscontroller');
mongoose.connect('mongodb://localhost:27017/STDBank');
app.use(bodyParser());
app.get('/', function (req, res) {
res.sendfile(__dirname + '/client/views/index.html');
});
app.use('/js', express.static(__dirname + '/client/js'));
//REST API
app.get('/api/tags', tagsController.list);
app.get('/api/tagnames', tagsController.listName);
app.post('/api/tags', tagsController.create);
app.put('/api/tagUpdate/:id', tagsController.update);
app.listen(3000, function() {
console.log('I\'m Listening...');
})
TaggingTool\server\models\tag.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TagSchema = new Schema({
request: String,
intentTag: String
}, {collection : "requests"});
module.exports = mongoose.model('Tag', TagSchema);
TaggingTool\server\models\name.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var nameSchema = new Schema({
name: String
}, {collection : "tags"});
module.exports = mongoose.model('TagName', nameSchema);
TaggingTool\server\controllers\tagscontroller.js
var Tag = require('../models/tag');
var TagName = require('../models/name');
module.exports.create = function (req, res) {
var tag = new Tag(req.body);
tag.save(function (err, result) {
res.json(result);
});
}
module.exports.listName = function(req, res){
TagName.find({}, function(err, results){
res.json(results);
});
}
module.exports.list = function (req, res) {
Tag.find({}, function (err, results) {
/*var arr = [];
for(var i = 0; i<results.length;i++){
if(results[i].intentTag){
console.log("enter if: ", results[i].intentTag);
}//end of if statement
else{
console.log("enter if: ", results[i].intentTag);
console.log("enters else statement ", arr);
arr.push({
_id : results[i]._id,
request : results[i].request
});
}//end of else statement
}//end of for loop
console.log("results ",arr);
*/
res.json(results);
});
}
module.exports.update = function(req, res){
console.log("Server side entered", res);
Tag.findByIdAndUpdate(req.params.id, {
$set: {
request: req.body.request,
intentTag: req.body.intentTag
}
}, function (err, tag){
if(err) res.send(err);
res.json(tag);
});
}
TaggingTool\client\js\controllers\tagsController.js
app.controller('tagsController', ['$scope', '$resource', function ($scope, $resource) {
var Tag = $resource('/api/tags');
var TagName = $resource('/api/tagnames');
var tagUpdate = $resource('/api/tagUpdate/:id');
Tag.query(function (results) {
$scope.tags = results;
});
TagName.query(function(results){
$scope.tagnames = results;
});
tagUpdate.query(function(results){
$scope.tags = results;
console.log("results: ", results);
});
//$scope.tags = [];
$scope.newtags=[];
console.log("tagReq", $scope);
$scope.newTag = function (index) {
console.log("newTag initiated");
var ntag = new tagUpdate();
console.log("_id: ", index);
var k = $scope.tagReq.request;
console.log("request: ", k);
var t = $scope.newTagName.tagname.name;
console.log("intentTag: ", t);
ntag._id = index;
ntag.request = $scope.tagReq.request;
ntag.intentTag = $scope.newTagName.tagname.name;
console.log("Tags: ", index);
$scope.ntag.$update({_id: index}, ntag);
}
$scope.createTag = function () {
var tag = new Tag();
tag.request = $scope.tagReq;
tag.intentTag = $scope.tagName;
tag.$save(function (result) {
$scope.tags.push(result);
$scope.tagName = '';
});
}
}]);
TaggingTool\client\js\app.js
var app = angular.module('taggingApp', ['ngResource'])
TaggingTool\client\views\index.html
<!DOCTYPE html>
<html ng-app="taggingApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tagging Tool </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<!-- Meetups View -->
<div ng-controller="tagsController">
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<caption><b><strong><em>Requests and their Tags</em></strong></b></caption>
<tr ng-repeat="tag in tags ">
<th ng-model="tagReq">{{tag.request}}</th>
<th>
<select ng-model="newTagName" ng-options="tagname.name for tagname in tagnames">
<option value="" >Select Tag</option>
</select>
<form ng-submit="newTag(tag._id)">
<input type="text" placeholder="Tag Name" ng-model="newTagName.tagname.name"></input>
<input type="submit"/>
</form>
<p>{{newTagName.tagname.name}}</p>
<p>{{tagReq.tag.request}}</p>
</th>
</tr>
</table>
<form ng-submit="createTag()">
<input type="text" placeholder="Tag name" ng-model="tagName"></input>
<button type="submit">Add</button>
</form>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-resource.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/controllers/tagsController.js"> </script>
</body>
</html>
I apologize for the terrible code and coding conventions, if anyone could help I would be extremely thankful.
I assume, this problem only occurs when you try to update from your Angular client? If so: Angular's $resource does not have an update method using PUT methods by default, see here.
You will need to define this manually, something along the lines:
$resource('/api/tagUpdate/:id', { id: '#_id' }, {
'update': { method: 'PUT' }
});
You can then use the resource's update method for performing your update.
Additional hint: With regards to REST conventions, I would not call the URL tagUpdate, but rather tags or something like this. The fact that you're updating is given by the HTTP method PUT already.

How do I get data to show up in angular ui.grid from an $http request continuation

Okay I'm going to keep this as short as possible.
I've been studying Angular for a bit now and there's still a lot I need to learn, right now I'm trying to figure out how to connect end to end with headers in a service which is completely new to me as I've never done end to end integration.
The code below is provided from another stack overflow answer and what I want to know is how do I connect what they have with say dataService.js. This is all new to me so I'm trying to ask this the best way possible.
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body ng-app="app">
<div ng-controller="gridController">
<!-- Initialise the grid with ng-init call -->
<div ui-grid="gridOptions" ng-init="GetGridData(urlList)">
</div>
</div>
<script src="Scripts/ng/angular.min.js"></script>
<script src="Scripts/ng-grid/ui-grid.min.js"></script>
<link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />
<script type="text/javascript">
var app = angular.module('app', ['ui.grid']);
app.controller("gridController",
["$scope", "$attrs", "$element", "$compile", "$http", "$q",
function ($scope, $attrs, $element, $compile, $http, $q)
{
$scope.urlList = "YourSourceUrl";
function fnGetList(url)
{
var deferred = $q.defer();
$http.get(url)
.success(function (data)
{
deferred.resolve(data);
})
.error(function (errorMessage)
{
alert(errorMessage);
deferred.reject;
});
return deferred.promise;
};
$scope.GetGridData = function (url)
{
console.log("In GetGridData: " + "Getting the data");
// Test Only - un-comment if you need to test the grid statically.
//$scope.loadData = ([
// {
// "UserName": "Joe.Doe",
// "Email": "Joe.Doe#myWeb.com"
// },
// {
// "UserName": "Jane.Doe",
// "Email": "Jane.Doe#myWeb.com"
// },
//]);
//return;
fnGetList(url).then(function (content)
{
// Assuming your content.data contains a well-formed JSON
if (content.data !== undefined)
{
$scope.loadData = JSON.parse(content.data);
}
});
};
$scope.gridOptions =
{
data: 'loadData',
columnDef:
[
{ field: 'UserName', name: 'User' },
{ field: 'Email', name: 'e-mail' }
]
};
}
]);
</script>
</body>
Provided from: How do I get data to show up in angular ui.grid from an $http request
The method I use is to pass the URL as an AJAX call and then wait for the data to get back after which I connect the JSON data to the ng-grid. Note that there will be a delay in getting the data back from the URL and you will have to have a timer that will keep checking for the data return begin valid.
function setCar(){
$.ajax({
type: "POST",
url: '/Test/ConfigConnect.json?details=&car='+car+'&id=1',
dataType: 'json',
success: function(data){
configData = data;
}
});}
The timer function that is part of the javascirpt is also given below.
var timer = setInterval(function() {
$scope.$apply(updatePage);
}, 500);
var updatePage = function() {
if (typeof configData !== 'undefined')
{
clearInterval(timer);
$scope.loadData = configData;
}
};

SequelizeJS Passing Array of Values

I am trying to figure out how it is possible to pass an array as the value for the property of an instance. I currently have the dataType set to STRING in my model and have values from jQuery fields insert each form field value into an array that I parse from the body and set to the property, discoverSource. Unfortunately I receive a string violation error that says I can't use an array or object. What does this mean and how can I change the dataType of the field or route to allow me to pass the comma separated values to the field?
E.x. For discoverySource I pass values to two fields (NJ, NY). On submit, the values are combined in an array as ["NJ", "NY"] and the error displays:
Error Message:
{"name":"SequelizeValidationError","message":"string violation: discoverySource cannot be an array or an object","errors":[{"message":"discoverySource cannot be an array or an object","type":"string violation","path":"discoverySource","value":["NJ","NY"]}]}
Here is my model:
module.exports = function(sequelize, DataTypes) {
var Organization = sequelize.define('organization', {
organizationId: {
type: DataTypes.INTEGER,
field: 'organization_id',
autoIncrement: true,
primaryKey: true
},
organizationName: {
type: DataTypes.STRING,
field: 'organization_name'
},
admin: DataTypes.STRING,
discoverySource: {
type: DataTypes.TEXT,
field: 'discovery_source'
},
members: DataTypes.STRING
},{
freezeTableName: true,
classMethods: {
associate: function(db) {
Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
},
},
});
return Organization;
}
Here is the route:
var express = require('express');
var appRoutes = express.Router();
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');
appRoutes.route('/sign-up/organization')
.get(function(req, res){
models.User.find({
where: {
user_id: req.user.email
}, attributes: [ 'user_id', 'email'
]
}).then(function(user){
res.render('pages/app/sign-up-organization.hbs',{
user: req.user
});
})
})
.post(function(req, res, user){
models.Organization.create({
organizationName: req.body.organizationName,
admin: req.body.admin,
discoverySource: req.body.discoverySource
}).then(function(organization, user){
res.redirect('/app');
}).catch(function(error){
res.send(error);
console.log('Error at Post' + error);
})
});
Here is my view file:
<!DOCTYPE html>
<head>
{{> head}}
</head>
<body>
{{> navigation}}
<div class="container">
<div class="col-md-6 col-md-offset-3">
<form action="/app/sign-up/organization" method="post">
<p>{{user.email}}</p>
<input type="hidden" name="admin" value="{{user.email}}">
<input type="hidden" name="organizationId">
<label for="sign-up-organization">Company/Organization Name</label>
<input type="text" class="form-control" id="sign-up-organization" name="organizationName" value="" placeholder="Company/Organization">
Add Another Discovery Source
<div id="sign-up-organization-discovery-source">
<input type="text" id="discovery-source-field" placeholder="Discovery Source" name="discoverySource[0]">
</div>
<br />
<button type="submit">Submit</button>
</form>
Already have an account? Login here!
</div>
</div>
<script type="text/javascript">
$(function() {
var dataSourceField = $('#sign-up-organization-discovery-source');
var i = $('#sign-up-organization-discovery-source p').size();
var sourceCounter = 1;
$('#sign-up-add-discovery-source').on('click', function() {
$('<p><label for="discovery-source-field"><input type="text" id="discovery-source-field" size="20" name="discoverySource['+ sourceCounter++ +']" value="" placeholder="Discovery Source" /></label> Remove</p>').appendTo(dataSourceField);
i++;
return false;
});
$('#sign-up-organization-discovery-source').on('click', '.remove', function() {
if (i > 1) {
$(this).parent('p').remove();
i--;
}
return false;
});
});
</script>
</body>
To answer the last comment, I need to be able to make the code more readable, so I'm posting it here in a new answer.
Having thought about it a little more, it would make more sense to add it as custom 'getter' function. I'll also include the 'instanceMethods' to demonstrate how that works, as well.
var Organization = sequelize.define('organization', {
...
},{
freezeTableName: true,
classMethods: {
associate: function(db) {
Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
},
},
// Here's where custom getters would go
getterMethods: {
discoverySources: function() {
return this.getDataValue('discoverySource');
}
},
// here's the instance methods
instanceMethods: {
getSourcesArray: function() {
return this.getDataValue('discoverySource');
}
}
});
Both of these options add the functions to each instance created by the Model. The main difference being in how they are accessed.
organization.discoverySources; // -> ['s1', 's2', etc...]
organization.getSourcesArray(); // -> ['s1', 's2', etc...]
note the additional () required on the instanceMethod. Those are added as functions of the instance, the getterMethods get added as properties.
setterMethods work the same way to allow you to define custom setters.
Hope that clarifies things a bit.

Node js how to handle file response

Hi i am trying to do ajax image upload.this is the work i got so far.
my index.html:
//index.html
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>File Upload showing Upload Progress</title>
<style>
* {
font-family: Verdana;
font-size: 12px;
}
</style>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="ImageFile" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="output"></div>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='main.js'></script>
</body>
<script type="text/javascript" src="js/jquery.form.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function() {
$(this).ajaxSubmit(options); //Ajax Submit form
// return false to prevent standard browser submit and page navigation
return false;
});
});
//function to check file size before uploading.
function beforeSubmit(){
alert('ok');
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
if( !$('#imageInput').val()) //check empty input filed
{
$("#output").html("Are you kidding me?");
return false
}
var fsize = $('#imageInput')[0].files[0].size; //get file size
var ftype = $('#imageInput')[0].files[0].type; // get file type
//allow only valid image file types
switch(ftype)
{
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
break;
default:
$("#output").html("<b>"+ftype+"</b> Unsupported file type!");
return false
}
//Allowed file size is less than 1 MB (1048576)
if(fsize>1048576)
{
$("#output").html("<b>"+fsize +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
return false
}
$('#submit-btn').hide(); //hide submit button
$('#loading-img').show(); //hide submit button
$("#output").html("");
}
else
{
//Output error to older unsupported browsers that doesn't support HTML5 File API
$("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
return false;
}
}
</script>
</html>
and my app.js
var express = require('express'); //Express Web Server
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path'); //used for file path
var fs =require('fs-extra'); //File System-needed for renaming file etc
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
/* ==========================================================
bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
app.route('/').get(function(req,res)
{
console.log("Server started!");
res.render('index.html');
res.end('done');
});
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(files);
res.send('fileinfo: ' +files);
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
I am getting the follwing response on server-side:
{ ImageFile:
{ domain: null,
_events: {},
_maxListeners: undefined,
size: 238027,
path: '/tmp/a7b06a71ff10de78cc8b941b18762b73',
name: 'bg.jpg',
type: 'image/jpeg',
hash: null,
lastModifiedDate: Sun Jun 01 2014 04:05:57 GMT+0530 (IST),
_writeStream:
{ _writableState: [Object],
writable: true,
domain: null,
_events: {},
_maxListeners: undefined,
path: '/tmp/a7b06a71ff10de78cc8b941b18762b73',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
pos: undefined,
bytesWritten: 238027,
closed: true } } }
Now i want to know.How to move this file into upload folder. And also when i submit it goes in another page.I want to perform it without reloading is there any way for it in node? Thanks in advance.
fs-extra module has move method. Use it like this:
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
fs.move(files.ImageFile.path, __dirname + '/upload/' + files.ImageFile.name, function(err) {
if (err) return console.log(err);
console.log('Moved successfully');
});
res.send('fileinfo: ' + files);
});
});
So the uploaded file appears in upload folder with the original name. There are 2 caveats:
upload folder should exist;
if file with such name exists already it will not be overwritten, so maybe you should generate a unique filename on each upload (replace files.ImageFile.name with your unique filename).

Categories