Angular doesn't work with Express and Pug - javascript

I have no idea why, but I can't force Angular working here. Does anybody have ideas of why this may be?
I can't even make a simple input form with binded model. There are always just {{model}} and this
File tree
/app.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/client'));
app.use(bodyParser.json());
require('./app/routes.js')(app);
app.listen(port, () => {
console.log('Server listening on port 3000...');
});
/app/routes.js
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/mes.db');
var _ = require('underscore');
module.exports = function (app) {
app.get('/messages', (req, res, next) => {
try {
var messages = [];
// Some db stuff
res.json(messages);
} catch (err) {
next(err);
}
});
app.set('views', './views');
app.set('view engine', 'pug');
app.get('*', (req, res) => {
res.render('index');
});
};
/client/controller.js
angular.module('myViewerController', [])
.controller('mainController', ['$scope','$http','Messages', function($scope, $http, Messages) {
$scope.formData = {};
$scope.loading = true;
Messages.get()
.success(function(data) {
$scope.messages = data;
$scope.loading = false;
})
.error(data => {
console.log('Error: ' + data);
});
}]);
/client/core.js
angular.module('myViewer', ['myViewerController', 'myViewerService']);
/client/service.js
angular.module('myViewerService', [])
.factory('Messages', ['$http', function ($http) {
return {
get: function () {
return $http.get('/messages');
}
}
}]);
/views/layout.pug
doctype html
html(ng-app='myViewer')
head
meta(charset='utf-8')
link(href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', rel='stylesheet')
body(ng-controller='mainController')
block content
block scripts
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js')
script(src='../client/controller.js')
script(src='../client/service.js')
script(src='../client/core.js')
/views/index.pug
extends layout
block content
.container(ng-controller='mainController')
.row
table.table-bordered
thead
tr
th Id
th Caller
th Message
th Date
tbody(ng-repeat='m in messages')
tr
td {{m.id}}
td {{m.caller}}
td {{m.text}}
td {{m.date}}

Thanks Muli Yulzary.
I've just changed
in
/app/routes.js
var path = require('path');
// ..
app.get('/', (req, res) => {
res.render('index', {root: path.join(__dirname, '../client')});
});
and in
/views/layout.pug
script(src='./controller.js')
script(src='./service.js')
script(src='./core.js')

Related

Express route isn't executed when JSON file is requested

I defined a route in my Express app that supposed to execute a line of code then return a JSON file, but what happens is that the file is returned, but the line of code isn't executed.
This is the server code:
var express = require('express');
var body_parser = require("body-parser");
var path = require('path');
server = express();
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
Inside index.html there is only a script tag defined like:
<body>
<script>
$(document).ready(function(){
$.getJSON("/request.json", function(data) {
console.log(data)
});
})
</script>
</body>
I can see the content of request.json file in chrome console, but the expected message "File "request.json" requested" isn't displayed on server's terminal.
Why the route isn't being executed?
The express.static is called before the /request.json route and already returns the file.
Use this:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
You can write custom static middleware. Can write logic to not to serve file[exclude].
Note: Note recommend from me, better change route name of /response.json
var express = require("express");
var path = require("path");
var app = express();
var statics = express.static(path.join(__dirname, "/"));
function customServe(secure) {
return function (req, res, next) {
console.log(req.path);
if (req.path != "/response.json") return statics(req, res, next);
return next();
};
}
app.use(customServe());
app.get("/response.json", (req, res) => {
console.log("something...");
res.send({ json: "json" });
});
app.listen(8080, () => console.log("working on 8080"));

issue with angular 4 and nodejs , serve index.html based on URL like /admin and /

Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})

Express.js req.body is returning nothing

I am learning node and express to create an api for an angular app I will be creating.
When I try and post something the req.body seems to be blank.
This is my server.js file
'use strict';
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
router = require('./api'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/my_db');
app.use(bodyParser.json());
app.use('/api', router);
app.get('/', function(req, res) {
res.render(__dirname + '/index.jade');
});
app.listen(3001, function() {
console.log('Listening on port 3001');
});
and this is my api/index.js file:
'use strict';
var express = require('express'),
Todo = require('../models/todo'),
router = express.Router();
router.get('/todos', function(req, res) {
Todo.find({}, function(err, todos) {
if(err) {
return console.log(err);
}
res.json({todos: todos});
});
});
router.post('/todos', function(req, res) {
var todo = req.body;
res.json({todo: todo});
});
module.exports = router;
when I use postman to post this to http://localhost:3001/api/todos:
{
'name': 'Walk the Dog',
'completed': false
}
my response is:
{
"todo": {}
}
I can't see why this would be blank, any help is appreciated.
UPDATE
Turns out I was posting text in postman instead of JSON.
use this in your server.js file
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

AngularJS + ExpressJS + mongoose: Add delete functionality

I am pretty new to AngularJS, and even newer to ExpressJS and Mongoose. I have been following a tutorial to post to, and get from my database, but I'm having trouble adding delete functionality.
Here is where I call my delete function:
<ul ng-repeat="disease in diseases">
<li>
{{ disease.name }}: {{ disease.chipped }},
{{ disease.received }},
{{ disease.smashed }},
{{ disease.complete }}
</li>
<button ng-click="removeDisease(disease)"></button>
</ul>
... and in my controller I have:
app.controller('MainCtrl', [
'$scope',
'TrelloApi',
'diseases',
function($scope, TrelloApi, diseases){
$scope.diseases = diseases.diseases;
$scope.removeDisease = function(disease) {
console.log(disease);
diseases.destroy(disease);
}
}
]);
...which calls my diseases factory:
app.factory('diseases', [
'$http',
function($http){
var o = {
diseases: []
};
o.destroy = function(disease) {
return $http.delete('/diseases/' + disease._id).success(function(data){
console.log("Disease " + disease.name + " has been removed!");
o.getAll();
});
};
return o;
}
]);
This returns with a 404 error:
DELETE http://localhost:4000/diseases/<id> 404 (Not Found) even though in my my routes include:
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Disease = mongoose.model('Disease');
// Not functional
router.delete('/diseases/:id', function(req, res, next) {
console.log(req);
});
// Functional
router.post('/diseases', function(req, res, next) {
var disease = new Disease(req.body);
disease.save(function(err, diseases){
if(err){ return next(err); }
res.json(diseases);
});
});
... and ui.router includes:
app.config([
'TrelloApiProvider',
'$stateProvider',
'$urlRouterProvider',
function(TrelloApiProvider, $stateProvider, $urlRouterProvider) {
.state('diseases', {
url: '/diseases/{id}',
templateUrl: '/javascripts/home/_diseases.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
]);
There is also a template found at /javascripts/home/_diseases.html. I have a feeling I am missing one piece but I just can't figure out what it is.
Be sure you start Express HTTP server:
const express = require('express');
const router = express.Router();
router.delete('/diseases/:id', function(req, res, next) {
const id = req.params.id;
console.log(id);
});
const app = express();
app.use('/', router);
const server = http.createServer(app).listen(8080, serverCallback);
function serverCallback() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server listening on ${host}:${port}`);
}

Why is Angualrjs not sending POST to my Express server?

I have a node Express server running on localhost that serves a page with angularjs code. When the user press a button on the page, there's an angularjs controller that post a json back to the server.
My problem is that the post doesn't seem to go to the server at all. I've checked the address and it's good. I've checked the button event and it does fire up. I'm really at a loss here. I'm new to the MEAN stack so is there something I'm doing wrong?
The route that handles the post(routes/blogposts.js):
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var URL = 'mongodb://localhost:27017/blog';
/* POST */
router.post('/', function(req, res, next) {
process.stdout.write("hello: ");
});
module.exports = router;
The angular controller that sends the post
app.controller('PostController', ['$scope', function($scope) {
$scope.sendPost = function() {
var id = document.getElementById("postTitle").value;
var type = document.querySelector('input[name="postType"]:checked').value;
var text = document.getElementById("postText").value;
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var date = ("<b>" + day + "/" + month + "/" + year + "</b>");
var sendObject = '{"id":' + id + ', "date": ' + date + ', "type":' + type + ', "post":' +
text +'}';
$http.post('http://localhost:3000/blogPosts', sendObject);
};
}]);
EDIT: added the code to the express router below
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 blogposts = require('./routes/blogposts');
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('/', routes);
app.use('/users', users);
app.use('/blogposts', blogposts);
// 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;
You need to inject $http into your controller like this:
app.controller('PostController', ['$scope', '$http', function($scope, $http) {
The angular stuff is posting to /blogPosts and not to /.
following what mop said. Your angularjs controller is posting to:
$http.post('http://localhost:3000/blogPosts', sendObject);
Honestly have no idea how to read your:The route that handles the post
I think by showing that you make it harder to understand!.
I don't think it adds any value to the question.
your code was confusing to read so i google it.
http://expressjs.com/starter/hello-world.html
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
you would need something more like...
app.post('/blogPosts', function (req, res) {
res.send('Hello World!');
});
but even if you did this it still feels fishy to me.

Categories

Resources