Im trying to use nodejs express v4 with stylus, but its throwing SyntaxError. Please help, also you can find my server.js below;;
Please note: Im first time creating MEANstack project, and dont be harsh on me :)
Your environment has been set up for using Node.js 0.10.26 (x64) and npm.
Error: Most middleware (like logger) is no longer bundled with Express and must
be installed separately. Please see https://github.com/senchalabs/connect#middle
ware.
at Function.Object.defineProperty.get (C:\Sites\meanProject\node_modules\exp
ress\lib\express.js:89:13)
at Object.<anonymous> (C:\Sites\meanProject\server.js:10:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
server.js:
var express = require('express');
var stylus = require('stylus');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
//set view engine
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
//style middlware
app.use(stylus.middleware({
src: __dirname + '/public',
dest: __dirname + '/public/css',
compile: function compile(str, path){
return stylus(str).set('filename', path).set('compress', true);
}
}));
app.use(express.static(path.join(__dirname + '/public')));//all public req will be responded by public dir now.
//load route
app.get('*', function(req, res){
res.render('index');
});
//start listening on server
var port = 3000;
app.listen(port);
console.log('Server running at localhost:' + port);
#thyforhtian yes, you were right my code was outdated.
I fixed it.
Im not using nodejs to compile my stylus file anymore, instead im using gulp.
Posting my file here, with steps, it might be helpful for someone-else.
Compile stylus files with gulp watch. And code for express server js file
Started with installing node modules
npm init
npm install -save express jade
// Step 1: Install gulp globally
npm install -g gulp
// Step 2: Install gulp in your project
npm install --save-dev gulp gulp-stylus gulp-plumber
npm install morgan body-parser --save
server.js
var express = require('express');
var stylus = require('stylus');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
//set view engine
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.urlencoded());
app.use(cookieParser());
//all public req will be responded by public dir now.
app.use(express.static(__dirname + '/public'));
//load route
app.get('*', function(req, res){
res.render('index');
});
//start listening on server
var port = 3000;
app.listen(port);
console.log('Server running at localhost:' + port);
gulpfile.js
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var plumber = require('gulp-plumber');
gulp.task('stylus', function() {
gulp.src('public/stylesheets/style.styl')
.pipe(plumber())
.pipe(stylus())
.pipe(gulp.dest('public/stylesheets'));
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.styl', ['stylus']);
});
gulp.task('default', ['stylus', 'watch']);
run gulp to execute
There seem to be a comma missing after src: __dirname + '/public'.
UPDATE
You should require and use it like this (first add it to package.json and npm install):
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser());
Related
I'm trying to setup a basic mean stack by following this guide, but the client doesn't seem to render the app instead the body contains,
<body>
<app-root></app-root>
</body>
The file structure is exactly the same as a blank angular cli project except the addition of two extra files.
PLUS: npm install --save ejs cors express body-parser
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cors = require('cors')
var index = require('./routes/index');
// app
var app = express();
// cors
app.use(cors());
// views
app.set('views', path.join(__dirname, 'src'));
// engine
app.set('view enginer', 'ejs');
app.engine('html', require('ejs').renderFile);
// angular dist
app.use(express.static(__dirname + '/dist'));
// body bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// route
app.use('/', index);
// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
I run an ng build and node server.js but get a blank white page in the browser.
Perhaps there is a breaking change that I'm not aware of since that guide was using angular2 (I'm using angular 6).
Since your index.html isn't directly inside the dist folder (rather, it is inside a sub-folder for some reason), try changing app.use(express.static(__dirname + '/dist')); to app.use(express.static(__dirname + '/dist/<your project name here>'));
I am trying to use express-handlebars view engine for express and I keep getting the following error:
Error: Cannot find module 'hbs'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at new View (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\view.js:81:14)
at Function.render (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\response.js:1008:7)
at C:\Users\WilPrim\Desktop\node-app\routes\routes.js:5:6
at Layer.handle [as handle_request] (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\router\route.js:137:13)
Here is my Code:
const express = require("express");
const bodyParser = require("body-parser");
const hbs = require("express-handlebars");
const router = require("./routes/routes");
//set up express app
var app = express();
app.use(bodyParser.json());
app.set('view engine', 'hbs');
app.set('views', './views');
app.set('view options', {layout: './layouts/layout'});
app.use(router);
According to the express-handlebars documentation, you have to setup and register the view engine manually:
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var hbs = exphbs.create({ /* config */ });
// Register `hbs.engine` with the Express app.
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// ...still have a reference to `hbs`, on which methods like `loadPartials()`
// can be called.
Looking a little bit further down in the documentation, looks like you can still use the .hbs extension with a bit of configuration:
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
use command -- sudo npm link hbs
you might have named the main folder as "express"
just change the name of folder,delete "package.json" and try
"npm install" again and then
"npm install express"
"npm install hbs"
/* been using this format for some time now, never had problems */
// import system modules
const hbs = require('express-handlebars');
const express = require('express');
const app = express();
// configuring express-handlebars as hbs
app.engine('hbs', hbs.create({
extname: 'hbs',
defaultLayout: 'main'
}).engine)
// system(app) routes
app.get('/', (req, res, next)=>{
res.render('home', {title: 'HBS TITLE'});
});
// system listening port
app.listen(8080);
install this module on terminal --> npm i hbs
try npm install and npm audit fix multiple times then rum the server after ex
I have done the standard MEAN stack JS application from scratch using Angular-CLI and node/npm. I did ng init and filled out some front end stuff which works fine when I use ng serve, then I created the back end using the code posted below and typing node server in shell. It loads my index.html page which is in src/index and then I try to do a join on src which contains src/app which has my Angular2 code but I get the dreaded Loading... from within my element. I have watched multiple tutorials and they all did exactly this or similar cookie cutter server code, I cannot figure it out.
server.js:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var event = require('./routes/events');
var port = 3000;
var app = express();
app.set('views',path.join (__dirname, 'src'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'src')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/', event);
app.listen(port, function() {
console.log("server listening on port" + port);
});
index.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
// res.render('../src/index.html');
res.render('index.html');
});
module.exports = router;
in Angular CLI app, run ng build or ng build --prod then node/express serve static directory dist not src.
I am trying to do my first ever node.js web server (local) however I can't seem to get it started, below is the code and the error message.
var app = require('express');
app.configure(function(){
app.set('port', 8080);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, '/public')));
}
app.listen(8080);
Error message
app.listen(8080);
^^^
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
You have many errors in your code. For example, the opening parenthesis on line 3 is never closed.
And it looks like you are trying to use some things that are currently deprecated in Express.
Here is your code modified to work with Express 3.20.2. You will get a pair of deprecation warnings but the code will work.
var path = require('path');
var express = require('express');
var app = express();
app.set('port', 8080);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, '/public')));
app.listen(8080);
The above code will not run as-is in Express 4. But hopefully this gets you started down a more productive path. If you are following along with a tutorial, find one that covers a more recent version of Express.
I do not know if you've already found an answer to your question... But when I look at the code, I see some missing brackets when requiring the express module.
var app = require('express');
Here is the example "Hello World" snippet from the express website
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
They have two lines of code that first includes the express module into the project as the variable "express". Then, they initialize a new express instance (not really, but almost the same):
var app = express();
and THEN they call all functions related to "app". The two first lines of code in the above example is the same as this one line code:
var app = require('express')();
And as you can see, you are missing two brackets.
I also want to point out that you are missing a closing bracket and semi-colon at the very end of your configure function. It should look like this:
app.configure(function(){
app.set('port', 8080);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, '/public')));
});
So... here is the final code:
var app = require('express')();
app.configure(function(){
app.set('port', 8080);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, '/public')));
});
app.listen(8080);
Unfortunately the logger and bodyParser middlewares is not longer bundled with express, so you have to install them separately. app.configure is also outdated, so you can get the code to work if you remove the configure function completely, and install the middlewares.
NOTE You are also using path which you have not included to your project install it and add this in the top:
var path = require('path');
So, without any middleware installation, this is the final code that works with the latest version of node and express:
var express = require('express');
var path = require('path');
var app = express();
app.set('port', 8080);
app.use(express.static(path.join(__dirname, '/public')));
app.listen(8080);
OR
var app = require('express')();
var path = require('path');
app.set('port', 8080);
app.use(require('express').static(path.join(__dirname, '/public')));
app.listen(8080);
In express 3.x
You miss ) at end of configure method
app.configure(function(){
app.set('port', 8080);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, '/public')));
});
you should follow the basic tutorial from ebook or internet.
e.g., https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
the simple node express app looks very clean and easy to learn
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I installed nodejs using homebrew just now.
I then created a folder, and installed express:
npm install -g express
I then created a new project using:
express -H --css less --sessions foo
Now when I try and run the app:
node app.js
I get this:
/Users/blah/dev/testing/nodetest1/foo/node_modules/less-middleware/lib/middleware.js:50
throw new Error('Please update your less-middleware usage: http://goo.gl/Y
^
Error: Please update your less-middleware usage: http://goo.gl/YnK8p0
at module.exports.less.middleware (/Users/blah/dev/testing/nodetest1/foo/node_modules/less-middleware/lib/middleware.js:50:11)
at Object.<anonymous> (/Users/snad/dev/testing/nodetest1/foo/app.js:26:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My app.js looks like:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I changed the line that was:
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
to:
app.use(require('less-middleware')(path.join(__dirname, 'public')));
and it works now. Strange how this was a brand new app with a fresh install of nodejs and express.
I commented out
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
entirely and achieved the same result. I feel that we are breaking functionality of some sort.