MEAN stack, angular basic example is not working - javascript

i am newbie to MEAN stack. i am making example from many websites.
but i just cannot go further.
here is the problem.
my webserver can send index.html and other js files.
but simple angular app won't work.
here are codes.
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-,8">
<title>BTELI</title>
</head>
<body>
<div ng-app="testApp">
<ng-view></ng-view>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="javascripts/app.js"></script>
</body>
</html>
app.js
var app = angular.module("testApp",[]);
app.config(function ($routeProvider) {
$routeProvider.when('/',
{
templateUrl: "view/main.html",
controller: "MainCtrl"
}
)
})
app.controller("MainCtrl", function ($scope) {
$scope.model = {
message:"This is MY APP!!!"
}
})
finally, main.html
<h1>{{model.message}}</h1>
i really don't have any idea why it won't works.
because, i could access to those js files in the html source.
what can i do?
i am not sure it helps or not, i attach my server side codes here.
app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.enable('jsonp callback');
app.set('view engine', 'ejs');
app.set('views',__dirname+'/public/view');
app.use(favicon(__dirname+'/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, '/public')));
require('./server/routes/index.js')(app);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env') === 'development') {
console.log('development mode');
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(80,function(){
console.log('Listening on Port 80');
});
module.exports = app;
and routing part.
app.get('/', function(req, res) {
res.sendfile('index.html');
});

Your app is not including the ngRoute service, and therefore wouldn't have access to the $routeProvider.
var app = angular.module("testApp",['ngRoute']);
in index.html
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.11/angular-route.js"></script>
https://docs.angularjs.org/api/ngRoute/service/%24route#example

Related

node js GET 404 (Not Found)

I am new to node.js. i am running nodejs from bin/wwww and getting "jquery.min.js:4 GET http://127.0.0.1:3000/file.js 404 (Not Found)" error. I am trying very basic and simple thing in a simple web page. Just trying to execute a file on server through ajax call but it always shows file not found error.
In my html page (firstpage.html) i am trying which i want as client request.
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link rel="stylesheet" type="text/css" href="stylesheets/myButton.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var dataString;
$(document).ready(function(){
$.ajax({
type: "GET",
url: 'file.js',
data: dataString,
success: function(data){
console.log(data);
}
});
});
</script>
</head>
<body>
<p class="auto-style1"><strong>Welcome to MyPage</strong></p>
<div >
<input class="myButton" type="button" onclick="readTextFile(test.txt)" value="Submit" />
</div>
<button id="bb">QUERY</button>
</body>
</html>
and i have a file (file.js) at server ,
var fs = require("fs");
console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
Currently file.js and index.txt are in myapp\public\javascripts location. my app.js is as below,
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var firstpage = require('./routes/firstpage');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Am i making some mistake in configuration ? please help.
Your express is never told what to serve when file.js is requested.
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Because it's not ., /users, or /firstpage it defaults to the 404 error and returns that. And because it's a js file, you need to use express's static middleware function.
app.use(express.static('routes');
Should be what you want, I would place it after
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
Such that:
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
app.use(express.static('routes');
Beware, this will allow anything in the routes folder to be accessed statically, so you're going to either want to move all your static resources somewhere else, or block off anything in the routes folder you don't want accessed this way.
Your ajax request point to the public folder but the file leaves in the javascripts subdirectory... Try moving the file you request in the public folder or change the request URL to point the correct folder structure...
Check this out: https://github.com/mdn/express-locallibrary-tutorial
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs
// Catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// Error handler
app.use(function(err, req, res, next) {
// Set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// Render the error page
res.status(err.status || 500);
res.render('error');
});

Passing an object into a pug/jade template with express

The basic problem is as follows:
Passing an object from my c# program, which is serialize and send through a socket. Achieved this in node.js/express application with socket.io.
Need to pass this to the client and using pug as the template engine.
Everything tried so far just doesn't seem to be working. Can't access the elements in the object. Pretty new to node and express so please bear with me.
app.js :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./app_server/routes/index');
var users = require('./app_server/routes/users');
var app = express();
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
layout.jade :
doctype html
html
head
meta(name='viewport', content='width=device-width, initial-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/amelia.bootstrap.css')
link(rel='stylesheet', href='/stylesheets/style.css')
script(src="https://cdn.socket.io/socket.io-1.4.5.js")
script.
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
body
block content
script(src='/javascripts/jquery-1.11.1.min.js')
script(src='/bootstrap/js/bootstrap.min.js')
index.jade :
extends layout
block content
h1= title
p Welcome to #{title}
//THIS IS WHERE I DON'T KNOW HOW TO ACCESS THE OBJECT AND ITS PROPERTIES
Can see the object in the console so the data is appearing.
Tried many different variations, but nothing seems to be working. Any input or guidance would be welcome.
Thanks in advance.

Consecutive Post request node JS

I wanted to know that
Can i do consecutive post requests in separate route file and with each post request redirect to a different ejs page.
This is my file structure
routes:-index.js
-users.js
-users1.js
views:-index.ejs
-users.ejs
-users1.ejs
this is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var users1 = require('./routes/users1');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/users1', users1);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
this is my index.js
`var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/users', function(req, res, next) {
res.redirect('/users');
});
module.exports = router;`
This is my index.ejs:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form action="/users" method="post">
<input type="submit" value="post">
</form>
</body>
</html>
this is my users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('users');
});
router.post('/users1', function(req, res, next) {
res.redirect('/users1');
});
module.exports = router;
this is my users.ejs
<html>
<head>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form action="/users1" method="post">
<input type="submit" value="post">
</form>
</body>
</html>
this is my users1.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('users1');
});
module.exports = router;
this is my users1.ejs
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>hello</h1>
</body>
</html>
the post request from index.ejs to users.ejs is working fine and it is redirecting to users.ejs
but the request from users.ejs to users1.ejs is not working .
and it shows 404 not found
this is the entire console.log output
> hostelSystem#0.0.0 start /home/ritwik/hostelSystem
> node ./bin/www
POST /users 302 43.621 ms - 56
GET /users 200 10.041 ms - 205
GET /stylesheets/style.css 304 2.742 ms - -
POST /users1 404 16.965 ms - 946
looks like in your users1 router you are using the router.get you probably want to use router.post because you are requesting domain.com/users1 it goes directly to this router only, and i only notice now that you dont need the forwarding because when you call domain.com/users it goes directly to the users router
router.post('/', function(req, res, next) {
res.render('users1');
});
module.exports = router;

express router not found

I created an express project using the express generator like following
express project_name
and
npm install
This is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
These are my routes
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'iDanG Management' });
});
module.exports = router;
I have following index.jade
extends layout
block content
div.container
div.row
form(id='myform' action='' method='post')
p Name:
input(type='text' name='name')
p E-Mail:
input(type='text' name='email')
input(type='submit' value='add')
table(class='table table-hover' id='user_table')
thead
tr
th Name
th Email
tbody
script.
$(document).ready(
function() {
$('#user_table').dataTable({
"pagingType": "simple_numbers",
"ordering": false
});
$('#myform').ajaxForm({ beforeSubmit:
function (formData, jqForm, options) {
$('#table').DataTable().row.add([formData[0].value, formData[1].value]).draw();
return false;
}
});
});
And following layout.jade
doctype html
html
head
title= title
script(src="/javascripts/jquery-1.11.2.min.js")
script(src="/javascripts/jquery.form.js")
script(src="/javascripts/jquery.dataTables.min.js")
link(rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css")
link(rel="stylesheet" href="/javascripts/jquery.dataTables.min.css")
body
block content
when I try to submit that form I receive following error:
Error: Not Found
at app.use.res.render.message (/home/ubuntu/iDanG_Management/app.js:30:13)
at Layer.handle [as handle_request] (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:302:13)
at /home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:321:12)
at next (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:261:10)
at /home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:603:15
at next (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:246:14)
at Function.proto.handle (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:166:3)
at router (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:35:12)
For the forms I used this
Do you have any suggestions how I can solve this problem? Help is highly appreciated!
It seems like you are doing a post request and your routes does not have post handler.
May be add route for post:
router.post('/', function(req, res, next) {
//do something and return data here?
});

Getting response after posting to mongodb

I tried testing my code written to post data to mongodb via postman using x-www-formurlencoded but I keep getting this error:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
at Layer.app.use.res.render.message [as handle] (c:\Users\Tomix\Documents\Source\Tomix\app.js:39:15)
at trim_prefix (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:226:17)
at c (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:198:9)
at Function.proto.process_params (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:251:12)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:189:19)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:166:38)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:150:14)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:166:38)
at Function.proto.handle (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:234:5)
at Layer.router (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:23:12)</pre>
</body>
<!--Live reload script -->
<script type="text/javascript" src="http://localhost:35729/livereload.js"></script>
</html>
So what am trying to do is to create an e-commerce website with mean stack,so am trying to structure the app files and folder to reflect the server side and the client side.
The code here is to save data to database (mongodb), but from the error message I was able to deduce is that at the point it ought to return response in json format it throws the error message.
exports.create = function(req, res) {
console.log('I got called', req.body);
var product = new Product(req.body);
product.save(function(err) {
if (err) {
return res.send(400, {
message: err
});
} else {
res.json(product);
}
});
};
My app.js file
'use strict';
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var routes = require('./routes/index');
var users = require('./routes/users');
/*connecting the to database*/
require('./config/db');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
next();
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
next();
});
//Routes
require('./app/routes/product.server.routes.js')(app);
exports = module.exports = app;
Please am stuck have search online for possible solution, some of the suggestion I got was I need to add method-override to my express configuration.
I think that you missed a part of the equation:
Post/Info -> Connector/Driver -> Mongodb/Database
Yo can not post JSON to mongo via Postma. You'll need to find a mongodb solution for javascript to play with it. You can try it with Node.js for example. Here I give you a list of all the language possibilities to connect to mongo.
http://docs.mongodb.org/ecosystem/drivers/
Hope it helps!

Categories