I'm having a problem connecting an express server with a gulp serve/r task. In order to send my views to the DOM, I need express to do that. I'd like my server to run as a gulp task. The server runs, however when I try to access my local url it runs an error in browser:
Error: Failed to lookup view "index" in views directory "C:\Users\User Name\Documents\project\src\scripts"
My app.js
var http = require('http');
var express = require('express');
var exphbs = require('express-handlebars');
var path = require('path');
var hbs = exphbs.create({ /* config */ });
var app = express();
//environment variable
var port = process.env.PORT || 8000;
// static files + template engine
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, '../scripts'));
app.use('/public', express.static(__dirname + '/public'));
//http request method get json list
app.get('/', function(req, res) {
res.render('index');
});
app.listen(port);
My file structure looks like this:
project
|-- src
| |-- css
| |-- scripts
| |-- app.js
| |-- index.html
What am I missing?
You should change this:
app.set('views', path.join(__dirname, '../scripts'));
to this:
app.set('views', path.join(__dirname, '..'));
This is because the index.html file resides in the src directory which is a parent of the scripts directory from which the script is executed.
Related
I have put my js in a public directory and trying to load the js in my HTML but getting an error.
var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
console.log(req.body);
console.log(req.file);
})
app.listen(3000,()=>{
console.log("server is up");
})
Here is my HTML code to load the JS:
<script src="/public/web.js"></script>
directory structure
├ public
| └ web.js
├ views
| └ some.ejs
└ server.js
To serve a file from the server to the client, you must declare the directory as a static.
Using express you can do this using,
app.use(express.static('PublicDirectoryPath'))
To fetch the files under the public directory,
<script src="FilePathUnderPublicDirectory"></script>
Updated Code:
Now your server.js file should be
var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
app.use(express.static('public'));
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
console.log(req.body);
console.log(req.file);
})
app.listen(3000,()=>{
console.log("server is up");
})
Notice that I declare the public directory as a static directory at
line 7.
Since your web3.js is directly under the public directory, in your front end, use
<script src="/web.js"></script>
For more, please check the doc.
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
app.use(express.static('public'))
now you can serve static files like js, css and images.
How can I make the following server.js code work for .html files instead on .ejs in Node JS. Thanks!
var express = require('express');
var app = express();
// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8080;
// set the view engine to ejs
app.set('view engine', 'ejs');
// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname + '/public'));
// set the home page route
app.get('/', function(req, res) {
// ejs render automatically looks in the views folder
res.render('index');
});
app.listen(port, function() {
console.log('Our app is running on http://localhost:' + port);
});
You should be able to just remove these lines:
// set the view engine to ejs
app.set('view engine', 'ejs');
// set the home page route
app.get('/', function(req, res) {
// ejs render automatically looks in the views folder
res.render('index');
});
and add your .html files to public/.
Testing this with this code
var express = require('express');
var app = express();
// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8080;
// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname + '/public'));
app.listen(port, function() {
console.log('Our app is running on http://localhost:' + port);
});
and this directory structure
├── package.json
├── public
│ └── index.html
└── server.js
Works fine for me.
My project structure looks like this:
project
assets/images/
css/application.css
js/application.js
font
node_modules
index.html
server.js
package.json
My goal is to be able to run 'node server.js" in the project folder and have it serve on port 80. Going to localhost:80 or w.e would render the index.html along with its css/assets/js.
I've tried with connect, express and http but no luck...new to node.
Thanks!
First of all, change your structure:
project
assets/images/
assets/css/application.css
assets/js/application.js
assets/font
node_modules
views/index.html
server.js
package.json
First require some packages:
var express = require('express'),
app = express(),
path = require('path');
Them run in the terminal window:
npm install express
Them set up the configurations:
app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
app.set('env', process.env.NODE_ENV || 'development');
app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder
Them create your routes:
app.get('/', function(req, res) {
res.send('Hello word');
});
app.get('/something', function(req, res) {
res.send('Hei, this is something!!!');
});
If you want render the index, inside the views folder:
app.get('/index', function(req, res) {
res.render('index');
});
And finally:
app.listen(app.get('port'), function(req, res) {
console.log('Server listening at ' + app.get('port')');
});
Them access localhost:80/index
Put your assets and subdirs under ./public, then from top dir, add app.js:
var express = require('express');
var app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(80, function () {
console.log('Server running...');
});
I'm writing a multi instance NodeJS application serving my Chrome extensions.
I think I got stuck in all that is related to subfolders, requiring and exporting modules.
Here's my app structure:
At the very bottom, I have start.js which bootstraps some major parts of the application like Express, models, views, controllers, routes, etc..
var express = require('express'),
http = require('http'),
arguments = process.argv.slice(2),
port = arguments[0] || 3000;
var app = express(),
server = app.listen(port),
io = require('socket.io' ).listen(server ),
routes = require('./config/routes')(app);
app.configure(function(){
"use strict";
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/app/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function() {
"use strict";
app.use(express.errorHandler());
});
console.log('Server is running on port ' + port);
module.exports = app;
In root folder of app, I have the instance files themselves. Like app.js (main), dealer.js (dealer instance), etc...
I run them like this:
[deb0rian#localhost www.bkbot.org]$ node ./app/dealer.js 3003
app/dealer.js itself for now is pretty simple:
var app = require('../start.js');
app.get('/', app.routes.dealer.index);
And my config/routes/index.js is:
var fs = require('fs' ),
required_files = [];
module.exports = function(app){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
And it fails to read my route files with this error:
[deb0rian#localhost www.bkbot.org]$ node ./app/dealer.js 3003
info - socket.io started
path.js:299
return splitPathRe.exec(filename).slice(1);
^
RangeError: Maximum call stack size exceeded
Is there something wrong with my file structure?
I want to be able to read only routes in /config/routers/dealer if I run that particular instance, no problem giving it command line argument, but i have to overcome this issue first and I don't know how to read only specific routes subdirectory.
Any help or advise will be appreciated!
Thanks
I want to use connect's vhost functionality to deploy several express.js apps to my dev vps. Here is my server.js file that is supposed to send requests to the appropriate place:
var express = require('express')
var quotes = require('quote-of-the-day/lib/app.js');
var server = express();
server.use(express.vhost('inspiringquoteoftheday.com',quotes));
server.listen(80);
Running node server.js throws this error:
Error: Cannot find module 'quote-of-the-day/lib/app.js'
Even though I can cd into app.js straight from the directory where server.js is located.
Here is the lib/app.js file in which I export my express app (I think)
// Generated by CoffeeScript 1.3.3
(function() {
var app, express, pub;
express = require('express');
module.exports = app = express();
pub = __dirname + '/public';
app.use(express["static"](pub));
app.use(express.errorHandler());
app.use(app.router);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function(req, res) {
return res.render('home');
});
}).call(this);
Assuming a directory structure that looks something like this:
|-. quote-of-the-day
|-- server.js <-- the file you list in your question
|-. lib
|-- app.js
Then you should require your app.js with
require('./lib/app');
Might be helpful to use the __dirname global variable here.
it provides 'the name of the directory that the currently executing script resides in.'
thus you could do:
var otherApp = require(__dirname + 'quote-of-the-day/lib/app.js')
http://nodejs.org/docs/latest/api/globals.html