Unable to load css file - angularjs

I am using express and nunjucks template engine for building a node app.
templateEngine.js
var nunjucks = require('nunjucks');
module.exports = function (app) {
// store environment env
var env = nunjucks.configure(['views/www'], {
autoescape: true,
express : app
});
}
app.js
var express=require('express'),
app=express(),
engines = require('consolidate'),
nunjucks = require('nunjucks');
MongoClient = require('mongodb').MongoClient,
http = require("http"),
assert = require('assert');
require('./templateEngine.js')(app);
app.set('view engine', 'html');
MongoClient.connect("mongodb://localhost:27017/firstDb",function(err,db){
assert.equal(null,err);
console.log("Sucessfully Connected to the Server");
app.get('/',function(req,res){
var query = {name : 'nobody'};
db.collection('friends').find().toArray(function(err,docs){
console.log(docs)
res.render('index',{'friendNames':docs})
})
})
})
var server = app.listen(3000,function(){
var port=server.address().port;
console.log('Express server listening on port', port);
})
When I tried to load
<link href="css/style.css" rel="stylesheet">
in index.html it says cannot get "http://localhost:3000/css/style.css"
my folder structure is
Root
views
www
css
style.css
index.html
app.js
templateEngine.js
If anybody encountered this error earlier, please help me. Thanks in advance!

Related

Angular js Expressions not working in Node js project

I have configure node js default project with express and using HTML page instead of JADE. I want to use Angular JS within HTML pages. Angular JS Simple examples are working fine in this project as :
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
Its working Fine. But if i am using {{name}} instead of ng-bind="name", its not working in this project.
For Example:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
This is not working in node project. Can anyone help me to find-out the issue.
App.js File code is as following:
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');
// Sql server new code
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var webconfig = {
user: 'sa',
password: '#####',
server: '######',
database: 'Test_Training',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
var sql = require('mssql');
// Sql server new code
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// To use simple html page
var cons = require('consolidate');
// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// To use simple html page
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(express.static(__dirname + '/public'));
app.use('/', index);
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 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;
Help will be appreciated.
The html engine is not supported out of the box.
(ref: https://github.com/expressjs/express/wiki#template-engines)
Solution given by #Thanh Tùng will work, but if you really want to set html as a view engine you should follow this solution
app.set('views', path.join(__dirname, 'views'));
// Set EJS View Engine
app.set('view engine','html');
// Set HTML engine
app.engine('html', require('ejs').renderFile);
Later you need to place your index.html inside /views directory
(original answer: https://stackoverflow.com/a/44945104/3627827)
EDIT: updated answer as suggested by #DanielZiga
First remove it :
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
I'm not sure about your strug folder but I guess file index.html of you in folder public . Try add this code in your node :
app.get('/*',function(req,res){
res.sendFile( index.html,{root:path.join(__dirname,public/index.html)});
})
You are using Swig as a Template Engine for your Server Side Rendering.
As you can see in its doc, Swig uses {{ and }} as interpolation delimiters... they're the same used by AngularJS.
What could happen is that Swig doesn't let your raw html reach the angular...
Try to change interpolation delimiters:
// https://docs.angularjs.org/api/ng/provider/$interpolateProvider
angular
.module('ModuleName')
.config(['$interpolateProvider', function($interpolateProvider) {
// set start symbol here
$interpolateProvider.startSymbol('^_^');
// set end symbol here
$interpolateProvider.endSymbol('"_"');
}])
;

How to display data in website created in Angularjs , data retrieved from SQL Server to Node.js

My company uses SQL Server. I want to develop reporting dashboard for it, and I want to develop it using Nodejs + Angularjs.
I have this following code; can you give me a small example of
Retrieve data from SQL Server
Display in html page using Angularjs
Use Node.js for the serverside program.
I have a piece of code. which is not working.
//server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/website'));
require('./app/routes.js')(app);
var server = app.listen(5000, function () {
console.log('Server is running..');
});
//router.js
module.exports = function(app) {
// Load index file
app.get('*', function(req, res) {
res.sendfile('./index.html'); // load the index from static files directory.
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'sqlserver',
server: 'FKHADER01',
database: "master"
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select count(*) CT from sales', function (err, recordset) {
if (err) console.log(err);
// send records as a response
res.send(recordset);
var count = recordset[0].CT;
});
});
});};
//index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script>
<body>
<div ng-app="" ng-init="count='5'">
<p>The name is <span ng-bind="count"></span></p>
</div>
</body>
</html>
Please provide me any other best method , if you have
I understand you are able to get the data from Sql server in your server.js Page. You would now want to send the data to the views.
So what you can do is use a view engine like EJS (npm install ejs)
and app.set('view engine', 'ejs');
you can pass the data which you have in the "recordset" variable to
the EJS page. The rendering would look something like
res.render('./index.ejs',message:recordset , count :count)
You would also need to create an index.ejs file and copy all the
context of index.html to it. The .ejs can simply be created
by renaming index.html to index.ejs
In the index.ejs , inside script tags ,you can retrieve the
recordset & count as
<script>var rawQuery = <%message%>; var count = <%count%></script>
You can then apply angular to manipulate the data in rawQuery,count
and attach it to the scope in the required controller.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = count;
});
Hope this link helps.
https://scotch.io/tutorials/use-ejs-to-template-your-node-application
I understand you are able to get the data from Sql server in your server.js Page. You would now want to send the data to the views. So what you can do is use a view engine like EJS (npm install ejs) and app.set('view engine', 'ejs'); you can pass the data which you have in the "recordset" variable to the EJS page. The rendering would look something like
res.render('./index.ejs',message:recordset , count :count)
You would also need to create an index.ejs file and copy all the context of index.html to it. The .ejs can simply be created by renaming index.html to index.ejs
In the index.ejs , inside script tags ,you can retrieve the recordset & count as
<script>var rawQuery = <%message%>; var count = <%count%></script>
You can then apply angular to manipulate the data in rawQuery,count and attach it to the scope in the required controller.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = count;
});
Hope this link helps. https://scotch.io/tutorials/use-ejs-to-template-your-node-application

Catch all routes loading blank page Angular NodeJs

I was working on Angular app with routing (NodeJs as backend). Routing through pages works fine but when I try to reload page it gives 'cannot load path /home'. I browsed through and got to few solutions like THIS.
My code is
app.get('*', function (req, res) {
res.sendFile('mypath/index.html');
});
But this loads up blank page. Is there any way I can solve this issue?
This us how my server.js looks like
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var port = process.env.PORT || 8080; // set our port
var staticdir = process.env.NODE_ENV === 'production' ? 'dist.prod' : 'dist.dev'; // get static files dir
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
//app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
//app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/' + staticdir)); // set the static files location /public/img will be /img for users
// routes ==================================================
app.set('views', __dirname + '/app');
app.set('view engine', 'html');
require('./devServer/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Starting sever on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
app.get('/', function (req, res) {
res.render('index', {
page: 'index'
}
});
then out this into your config,
app.set('views', 'directory where index.html is');

Why Angular says that cross origin request occurs when there's actually no any?

I am trying to serve Angular application using ExpressJS. Here is my index.js:
var express = require('express');
var path = require('path');
var app = express();
app.set('port', (process.env.PORT || 8000));
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname + 'fake_data')));
// views is directory for all template files
app.set('views', __dirname + '/app/pages');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', function(request, response) {
response.render('index');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
In my angular app there is also a constant containing API server address:
(function () {
angular.module('Bankbox')
.constant('webConfig', {
API_SERVER: ''
});
})();
It is been set during run phase:
(function () {
angular.module('Bankbox')
.config(bankboxConfig)
.run(runConfig);
function runConfig($location, webConfig){
var port = ":" + $location.port() + "/";
webConfig.API_SERVER = $location.host();
if (port){
webConfig.API_SERVER += port;
}
}
.....
Finally when i execute node index.js, and trying to load 'localhost:8000' in the browser i get an error:
XMLHttpRequest cannot load localhost:8000/fake_data/my-deals.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
The GET request is in a factory and it looks like:
function getMyDeals() {
return $http.get(webConfig.API_SERVER + 'fake_data/my-deals.json')
.then($http.getDataFromResult);
}
Why this happens? I assumed that localhost:8000 shouldn't think of itself as an another origin.

How to enable HTML5 mode in Express without breaking NodeMailer?

everyone. I'm making my first Node + Express + Angular app.
I kinda used https://github.com/codeschool/StayingSharpWithAngularSTB as a boiler plate.
The general layout is
[folder] app
--------- [Sub-Folder] Assets (Javascript, css, images etc.)
--------- [Sub-Folder] Pages (This contains ng-view stuff)
--------- [Sub-Folder] Views
-------------------- index.html (This is the main index.html that holds everything together)
[folder] node_modules
[folder] server
--------- [Sub-Folder] Controllers
---------------------- core.server.controller.js
--------- expressConfig.js
--------- routes.js
app.js
package.json
So here's the my server configuring files:
app.js
var app = require("./server/routes");
// Start the server
var port = process.env.PORT || 8000;
app.listen(port, function(){
console.log('Listening on port ' + port);
});
/server/expressConfig.js
var bodyParser = require('body-parser');
module.exports = function(app, express) {
// Serve static assets from the app folder. This enables things like javascript
// and stylesheets to be loaded as expected. You would normally use something like
// nginx for this, but this makes for a simpler demo app to just let express do it.
app.use("/", express.static("app/"));
// Set the view directory, this enables us to use the .render method inside routes
app.set('views', __dirname + '/../app/views');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
};
/server/routes.js
var express = require('express');
var app = express();
var core = require('./controllers/core.server.controller')
// Load Express Configuration
require('./expressConfig')(app, express);
// Root route
app.get('/', function(req, res){
res.sendfile('index.html', {root: app.settings.views});
});
// routes for sending forms
app.route('/contact-form').post(core.sendMail);
app.route('/table-form').post(core.sendTableRes);
app.route('/artist-form').post(core.sendArtistRes);
module.exports = app;
/server/controllers/core.server.controller.js
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: //my gmail,
pass: //my gmail password
}
});
// Send an email when the volunteer form is submitted
exports.sendMail = function (req, res){
var data = req.body;
transporter.sendMail({
from: //my gmail,
to: //another gmail,
subject: data.volunteerName+ ' wants to volunteer for our event 2016',
text: 'Volunteer Info \n Name : '+data.volunteerName+'\n Phone Number : '
+data.volunteerNum+'\n E-mail : ' +data.volunteerEmail
});
res.json(data);
};
// Other similar mailing functions
And here's one of the angular controllers that sends the mail
volunteerFormController.js
angular.module('MyApp').controller('FormController', function($http){
this.volunteer = {
};
this.addVolunteer = function(){
var data = ({
volunteerName : this.volunteer.name,
volunteerEmail : this.volunteer.email,
volunteerNum : this.volunteer.phone
});
$http.post('/contact-form', data).
then(function(response) {
//show thank you message with animate.css classes and hide form
$(".thanksFriend").addClass("animated tada showBlock");
$("form").addClass("flipOutX animated hideBlock");
}, function(response) {
$(".sorryFriend").addClass("animated tada showBlock");
});
};
});
And this works just fine! But if I enable html5 mode in Angular and serve up the index in Express using
app.use(function(req, res){
res.sendfile('index.html', {root: app.settings.views});
});
in the routes.js file, Html 5 mode works great! No 404s when I remove the pound and refresh but then the none of my contact forms work, and the console isn't giving me any errors... My server files are pretty small and it's not super complicated so it should be pretty easy to figure out how to have both HTML5 mode AND working contact forms. Any ideas? I don't know much about Express and I used a tutorial http://www.bossable.com/1910/angularjs-nodemailer-contact-form/ to figure out how to use nodemailer. Is there another way to set up nodemailer so this works?
I would REALLY appreciate some help with this. It's driving me absolutely crazy ;__;
So, you had to serve every request return index.html,
by changing app.get('/', to app.get('/*',

Resources