template to transform html code - javascript

I write a simple program which is really unreadable. At first, I didn't know how to use template so I decide, in spite of that, to write html code inside my node.js code.
(solved)

Try something like this
I usually have a project structure like:
lib
node_modules
public (This is where the CSS and page JS goes)
routes
views (This is where you put your EJS templates)
app.js
In your package.json make sure you have included ejs
"ejs": "*"
In app.js (assuming you use express)
var express = require("express");
var app = express();
var routes = require("./routes/routes.js");
//Other setup code
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
//Here is an example HTTP route
app.get('/home', routes.view_page);
//Other Server code
And then in routes.js
exports.view_page = function (req,res){
var customMessage = "Hello, Node is awesome";
res.render("view", {
msg:customMessage
});
};

I think your .ejs file is fine, this is a very minimal express server that works with your example:
app.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var customMessage = "My Message";
res.render('view.ejs', {msg:customMessage });
});
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);
});
then use your view.ejs and put it in the sub-folder views/

Related

How to prevent node js from serving .git folders and all the files under .git

I know that using .htaccess file can restrict files to be served under .git but how do i acheive the same if i'm using node.js server. I use forever to start/stop the servers.
Below is the code.
const bodyParser = require("body-parser");
var request = require("request");
const dotenv = require('dotenv');
const app = express();
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname));
app.set('view engine', 'ejs');
dotenv.config();
var environment = process.env.NODE_ENV;
var endpoint = process.env.AUTOMATION_API_ENDPOINT;
var port = process.env.PORT;
console.log('Environment : '+ environment);
console.log('Server Port : '+ port);
console.log('BackEnd server Endpoint : '+ endpoint);
var supplierId = null;
var supplyApiEndpoint = null;
app.get("/", function(req,res,next){
var env=null;
var url = endpoint+'/v1/supply/qa/env';
require('http').get(url, (resp) => {
resp.setEncoding('utf8');
resp.on('data', function (response) {
var body = JSON.parse(response);
var supplyApiEndpoint = body.endpoint;
console.log("Endpoint: "+supplyApiEndpoint);
res.render('index',{env: supplyApiEndpoint});
});
});
})```
The forever is a tool for ensuring that a given script runs continuously and not a web framework.
To serve your files you will need to use a web framework like express and you will be able to ignore some directories serving only the files you need, for example, to serve your views directory:
app.set('views', path.join(__dirname, '/yourViewDirectory'));
or adding some rules using regex to ignore the files:
app.use([/^\/public\/secure($|\/)/, /(.*)\.js\.map$/, '/public'], express.static(__dirname + '/public'));
You can use other node.js web frameworks to do the same as fastify or koa.

react app with express.js route setup

I was using angular.js and I do this in express.js
app.get("*", function (req, res) {
res.redirect('/#' + req.originalUrl)
})
so that the browser will use the route of angular instead of express. But how to do that with react router? I have 2 folder, named server and client, server folder has express and api logic while client folder simply a react app.
You need to put the path in of the HTML file you are rendering your app to
app.get("/",(res,res) => {
res.sendFile('put the path of the html file you are rendering your app into here');
}
here is an example of a express server.js that works with react
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
app.use(express.static('./public'));
app.get('/', function(req,res){
res.sendFile('./public/index.html');
});
app.listen(PORT, function(){
console.log("Listening on port: " + PORT);
});

Unable to render index.html file from my view folder in angular2

I'm creating a MEAN Stack application where angular has setup in /client folder. I want that when I run npm start command in /client folder it should render index.html file from /views folder, what I'm doing wrong getting this error
Cannot GET /
Folder structure is as follows.
meanApp
----- client (angluar2 setup here but doesn't have an index.html file)
---------- app
----- views
----------index.html
----- routes
----- server.js
Codes in server.js
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var index = require('./routes/index');
var tasks = require("./routes/tasks");
var app = express();
//View engines
app.set("views", path.join(__dirname,'views'));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Set static folder
app.use(express.static(path.join(__dirname,'client')));
// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/', index);
app.use('/index', index);
app.use('/api', tasks);
//listen
app.listen(3000, function(){
console.log("Server listing # 3000");
});
Here you need to define route for express server like :
app.set('appPath', 'client'); //this is a folder where your index.html is
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
This will cause every call in broweser to render index file.
const http = require('http');
fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();
app.set('appPath', 'views');
app.use(express.static(__dirname + '/views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use('/*', function(req, res, next) {
res.sendfile(app.get('appPath') + '/index.html');
});
http.createServer(app).listen(3001, function() {
console.log(`Express server listening on port 3001`);
});
exports = module.exports = app;

Hosting a static Node.js page

I'm trying to learn about Node.js and I have written a simple Node.js page with express and ejs by following a guide at Lynda.com. I have the page hosted on an Amazon AWS server and have Nginx installed. I can access the page at IP:3000 when I'm running the node app. I have also set up Nginx following several different guides to redirect the servers IP/ to port 3000. However when I try and access the page at IP/ none of the images or the CSS show up.
I have set up some webpages in the past for school using Ruby on Rails and I'm assuming that this is a development vs production issue. Most guides/instructions I find just show setting up Nginx for a simple hello world app without any images or CSS. Can someone direct me to the proper resource to accomplish what I'm trying to do here?
Edit: Here are my app.js and my two routes
app.js
var express = require('express');
var reload = require('reload');
var app = express();
var clientFile = require('./data/clients.json');
var instructionFile = require('./data/instructions.json');
app.set('port', process.env.PORT || 3000);
app.set('clientData', clientFile);
app.set('instructionData', instructionFile);
app.set('view engine', 'ejs');
app.set('views', './views');
app.locals.siteTitle = 'Roux Meetups';
app.use(express.static('./public'));
app.use(require('./routes/index'));
app.use(require('./routes/instructions'));
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
reload(server, app);
var express = require('express');
var router = express.Router();
route 1
router.get('/', function(req, res) {
var clients = req.app.get('clientData');
var clientPhotos = clients.images;
var clientAddresses = clients.sites;
res.render('index', {
pageTitle: 'Home',
clients: clientPhotos,
sites: clientAddresses,
pageID: 'home'
});
});
module.exports = router;
route 2
var express = require('express');
var router = express.Router();
router.get('/instructions', function(req, res) {
var clients = req.app.get('clientData');
var clientPhotos = clients.images;
var clientAddresses = clients.sites;
var instructions = req.app.get('instructionData');
var instructPhotos = instructions.images;
res.render('instructions', {
pageTitle: 'Instructions',
clients: clientPhotos,
sites: clientAddresses,
instructs: instructPhotos,
pageID: 'instructions'
});
});
module.exports = router;
I also have only edited my /etc/nginx/sites-available/default for nginx with the following
server {
listen 80 default_server;
listen[::]:80 default_server;
root /var/www/html;
index index.html index.html index.nginx-devian.html;
server_name _;
location / {
proxy_pass http://localhost:3000;
try_files $uri $uri/ = 404;
}
}
So my issue was that my /etc/nginx/sites-available/default was configured way wrong. I had edited it with garbage and totally forgotten that. Leaving this up though in case anyone else has a similar question. The correct nginx configuration I got from https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04

node.js TypeError: Object has no method get

I'm trying to separate server initiation and other calls from the core file(app.js) but when I try to run it, it issues me error that
http.createServer(app).listen(app.get('port'), function(){
^
TypeError: Object function (){ all code from app.js file }
has no method 'get'
This is app.js file.
/**
* Module dependencies.
*/
module.exports = function(){
var express = require('express');
var routes = require('./routes');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 4000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
return app;
};
and this is server.js file.
var http = require('http'),
app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
using express#3.4.0
what am I missing OR doing wrong.. please help.
You have no reason to return a function into your app.js file, just return the express object:
var express = require('express');
var app = express();
// ... more variables
// ... the rest of your code
module.exports = app;
Then, the rest of your code into server.js will work fine.
Remember that module.exports works like a "return" into CommonJS (and therefore NodeJS).
See documentation.
You're passing a function to module.exports, so when you require('./app'), you need to call it like a function:
var http = require('http'),
app = require('./app')();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

Categories