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)
})
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 just deployed my express.js server on openshiftapps and for some reason, one of the routes not working and I get :
Internal Server Error
Same route is fine in local.this route is my root route which only should render my index.ejs file. the other routes working just fine. I share the codes here, I hope you guys can help to see where did I do wrong.
So this is my server.js code :
var express= require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var accountname = require('./routes/accountname');
var app = express();
//View Engine (We Use ejs)
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'ejs');
// app.use(express.static(path.join(__dirname,'edaccounting')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api/v1/', accountname);
app.listen(8080, function(){
console.log('Server is Started on port 8080');
})
And this is my index.js :
var express= require('express');
var router = express.Router();
router.get('/',function(req,res,next){
res.render('INDEX');
})
module.exports = router;
so for this route : app.use('/', index); I get Internal server error on the real server but it's working in my local and render the .ejs file. Other route is fine in real server. I used openshiftapps and I build my node.js app there with no errors!
I'm learning MEAN stack with 'Getting MEAN with...' book, and problem is older Express version in books than i use.
The first step is to tell our application that we’re adding more routes to look out for,
and when it should use them. We already have a line in app.js to require the server
application routes, which we can simply duplicate and set the path to the API routes
as follows:
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
Next we need to tell the application when to use the routes. We currently have the following line in app.js telling the application to check the server application routes for
all incoming requests:
app.use('/', routes);
Notice the '/' as the first parameter. This enables us to specify a subset of URL s for
which the routes will apply. For example, we’ll define all of our API routes starting
with /api/ . By adding the line shown in the following code snippet we can tell the application to use the API routes only when the route starts with /api :
app.use('/', routes);
app.use('/api', routesApi);
And there's listing of my app.js file:
var express = require('express')
, others = require('./app_server/routes/others')
, locations = require('./app_server/routes/locations')
, routesApi = require('/app_api/routes/index')
, ;
require('./app_server/models/db')
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/app_server/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
// LOCATION PAGES
app.get('/', locations.homeList);
app.get('/location', locations.locInfo);
app.get('/location/review/new', locations.addReview);
// OTHER PAGES
app.get('/about', others.about);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
Can someone explain me how to do the same in my Express version ?
In Express 4, this is done using Router Middleware. More info is available on Express Routing here.
A Router is simply a mini express app that you can define middleware and routes on that should all be packaged together, ie /api should all use apiRouter. Here is what apiRouter could look like
apiRouter.js
var express = require('express')
var router = express.Router(); // Create our Router Middleware
// GET / route
router.get('/', function(req, res) {
return res.status(200).send('GET /api received!');
});
// export our router middleware
module.exports = router;
Your main Express app would stay the same, so you would add your router using a require() to import the actual file, and then inject the router with use()
Express Server File
var express = require('express');
var app = express();
var apiRouter = require('../apiRouter');
var port = process.env.PORT || 3000;
app.use('/', apiRouter);
app.listen(port, function() {
console.log('listening on ' + port);
});
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());
I don't seem to get JSHTML to work as a template engine on Express.js in Node.js. When I install my Express.js application and a basic application is created for me, and I run it I get this error message:
500 TypeError: Property 'engine' of object #<View> is not a function
at View.render (/Users/blackbook/nodejs/ds/node_modules/express/lib/view.js:75:8)
at Function.app.render (/Users/blackbook/nodejs/ds/node_modules/express/lib/application.js:504:10)
at ServerResponse.res.render (/Users/blackbook/nodejs/ds/node_modules/express/lib/response.js:677:7)
at exports.index (/Users/blackbook/nodejs/ds/routes/index.js:7:7)
at callbacks (/Users/blackbook/nodejs/ds/node_modules/express/lib/router/index.js:165:11)
at param (/Users/blackbook/nodejs/ds/node_modules/express/lib/router/index.js:139:11)
at pass (/Users/blackbook/nodejs/ds/node_modules/express/lib/router/index.js:146:5)
at Router._dispatch (/Users/blackbook/nodejs/ds/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/blackbook/nodejs/ds/node_modules/express/lib/router/index.js:33:10)
at next (/Users/blackbook/nodejs/ds/node_modules/express/node_modules/connect/lib/proto.js:190:15)
My app.js looks like this (it's what Express.js created for me):
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jshtml');
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')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
I have this installation:
Node.js v.0.8.5
Express.js#3.0.0rc2
jshtml#0.2.3
JSHTML currently works with Express.js 2. There are plans on getting the engine to work with Express.js 3, but currently I am too busy with enjoying the summer! Expect a fix for this problem in the winter!
According to https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x you can use app.engine for 2-x compatibility.
e.g.
var fs = require("fs");
var jshtml = require("jshtml");
app.engine("jshtml", function (path, options, fn) {
fs.readFile(path, 'utf8', function (err, str) {
if (err) return fn(err);
str = jshtml.compile(str,options)(options).toString();
fn(null, str);
});
});
consolidate.js is used as a bridge between many template engines and express. If your engine isn't supported checkout the source code. Most engines need like 15 lines of code to implement.
I have it working in my project and will probably issue a pull request soon but for now look at my comment in
https://github.com/elmerbulthuis/jshtml/issues/5
Try the following. It works for me, as like you.
Firstly, install jshtml-express via npm and then do the following.
var app = express();
**app.engine('jshtml', require('jshtml-express'));**
// All environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jshtml');
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')));
I hope it will work for you as well.