Express has no method configure error - javascript

I'm trying to get started with the MEAN stack. And I'm following this tutorial: link
I have made it until the Test Our Server section. Here
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
// configuration ===========================================
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
When I run
nodemon server.js
I get this error
app.configure(function() {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (C:\Users\Yuksel\Desktop\node\test\server.js:14:5)
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
5 Mar 17:27:20 - [nodemon] app crashed - waiting for file changes before startin
g...
It simply says app has no method configure(I guess). But when I delete the configure part and run it again, it works.(This mean app has .listen method, so it is an express object.)
I have tried with both node and nodemon. And I couldn't figure it out. Thank you for your time.

Tom in his blog post new-features-node-express-4 provides examples of how to convert from using app.configure in express version 3.x to removing it in express version 4.0.
For convenience I added the code example below.
Version 3.x
// all environments
app.configure(function(){
app.set('title', 'Application Title');
})
// development only
app.configure('development', function(){
app.set('mongodb_uri', 'mongo://localhost/dev');
})
// production only
app.configure('production', function(){
app.set('mongodb_uri', 'mongo://localhost/prod');
})
Version 4.0
// all environments
app.set('title', 'Application Title');
// development only
if ('development' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/dev');
}
// production only
if ('production' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/prod');
}

The configure method has been removed from express as of version 4.0.0 (including 4.0.0-rc2). See the changelog at https://github.com/strongloop/express/blob/master/History.md#400--2014-04-09

Related

how to run an ExpressJS application

Nothing seems to work except the "throw new Error" in my code, I have installed all the necessary packages I'm sure. I am getting no errors in other places of my code. I can't seem to find the problem. Hoping someone knows how to solve this.
const express = require('express'); // we're making an ExpressJS App
const bodyParser = require('body-parser'); // we'll use body-parser extensively
//const port =3000
const app = express(); // create the ExpressJS app
// parse the different kinds of requests (content-type) the app handles
// use the "use" method to set up the body-parser middlewear
app.use(express.json()) // application/json
app.use(express.urlencoded({ extended: true })) // application/x-www-form-urlencoded
// Set up Mongoose and our Database connection
const dbConnect = require('./config/AtlasConnect.js');
const mongoose = require('mongoose');
// Set up connection to the database
mongoose.connect(dbConnect.database.url, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Successfully connected to the MongoDB database");
}).catch(err => {
console.log('Unable to connect to the MongoDB database', err);
process.exit();
});
throw new Error("NOT WORKING!");
// // create our test route (reply by sending a JSON message as response)
// app.get('/', (req, res) => {
// res.json({"message": "My Phone Shop App. Use the app to manage your favourite s!"});
// });
require('./app/routes/Users.routes.js')(app);
// listen for requests on port 3000
app.listen(3000, () => {
console.log("Server listening on port 3000");
});
This is the error I get in terminal:
PS C:\Users\jaffe\Documents\assignment-06-17518623> node assignment-06.js
C:\Users\jaffe\Documents\assignment-06-17518623\assignment-06.js:44
throw new Error("NOT WORKING!");
^
Error: NOT WORKING!
at Object.<anonymous> (C:\Users\jaffe\Documents\assignment-06-17518623\assignment-06.js:44:7)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
Line throw new Error("NOT WORKING!"); always throws exception, and stops code execution.
See documentation https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Statements/throw

Unexpected Token ILLEGAL on running node.js

I'm doing a programming course and I'm trying to run the command node server.js. However this is the result I get.
node server.js
/home/lalitp/webapp/imad-app/server.js:26
console.log(`IMAD course app listening on port ${port}!`);
^
SyntaxError: Unexpected token ILLEGAL
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:902:3
This is the server.js file:
var express = require('express');
var morgan = require('morgan');
var path = require('path');
var app = express();
app.use(morgan('combined'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'index.html'));
});
app.get('/ui/style.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'style.css'));
});
app.get('/ui/madi.png', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'madi.png'));
});
// Do not change port, otherwise your app won't run on IMAD servers
// Use 8080 only for local development if you already have apache running on 80
var port = 80;
app.listen(port, function () {
console.log(`IMAD course app listening on port ${port}!`);
});
Thanks for the help :)
You are probably using an older version of Node.js, which does not support the so-called back-tick quoted strings (surrounded by the ` character).
If you change
console.log(`IMAD course app listening on port ${port}!`);
to
console.log('IMAD course app listening on port ' + port + '!');
it should work.
The back-tick quoted strings are for interpolating variables, i.e. integrating a JavaScript expression into a string. This makes long strings with lots of variables easier to read than concatenating every single bit by using the + operator.
It seems that you're using ES5 and not ES6 so you cannot use ` token for a string :
console.log('IMAD course app listening on port ${port}!');

TypeError: PUBNUB.init is not a function

I am using Node.js and I'm trying to get PubNub integrated to get my chatroom up and running. I have been following numerous tutorials and they all seem to have PubNub executing from their client-side. However, to ensure the security of my publish-key and subscribe-key I want to have PubNub execute from my server-side (Nodejs). However the problem is occurs exactly when I try to do just that. Here is my server:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var request = require('request');
var pubnub = require('pubnub');
pubnub = pubnub.init({
subscribe_key: 'sub-c-demo',
publish_key: 'pub-c-demo',
ssl: true
});
//Defining routes
var routes = require('./routes/index');
//Init express
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//View Engine
app.set('view engine', 'ejs');
//Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
//Get route
app.use('/', routes);
//Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('3000 is the magic port!!');
});
Why do I get a TypeError: pubnub.init is not a function when I try to initialize pubnub?
$ node server
/Users/macbookpro/Desktop/project007/server.js:8
var pubnub = pubnub.init({
^
TypeError: pubnub.init is not a function
at Object.<anonymous> (/Users/macbookpro/Desktop/project007/server.js:8:21)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3
I followed what seemed to be all the necessary steps:
npm i pubnub --save
var pubnub = require('pubnub');
https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.2.min.js
(Included the latest sdk in my header)
But there seems to be an error somewhere which has lead to me to be confused about the error as well as a few other things.
1). I have been piecing things together from all three but which of these tutorials should i really be following?
https://vimeo.com/35557579
https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4
https://www.pubnub.com/docs/javascript/pubnub-javascript-sdk-v4
2). Does my publish-key and subscribe-key need be secured or can I simply run PubNub from my client-side like shown in most tutorials?
3). Forget about the server-side and client, should I be executing PubNub as a javascript file and linking the script? <script src="js/pubnubchatroom.js"></script>
I am new to this stuff and im just trying to wrap my head around it all. Thanks in advance!
PubNub V4 SDK NodeJS new Init
There is a new way to initialize your PubNub SDK. See the following example. v4 SDKs are not drop-in compatible. You can mix v4 and v3 SDKs between environments successfully.
const PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})
Follow https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4
pub/sub keys can be exposed. never expose your secret key.
PubNub is compatible with any strategy in this regard.

Cannot GET /cool on Heroku nodejs tutorial locally

Here are the dependencies of my package.json file where i've added "cool-ascii-faces. I then need to update my index.js file to GET the /cool page so that on each reload I would see an ascii face. I'm getting a 404 error and it says 'Cannot GET /cool'
"dependencies": {
"ejs": "2.3.3",
"express": "4.13.3",
"cool-ascii-faces": "~1.3"
}
Below is my index.js file that calls declares cool
var cool = require('cool-ascii-faces');
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/cool', function(request, response) {
response.render('pages/index')
});
app.get('/cool', function(request, response) {
response.send(cool());
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
I then run npm install to update the dependencies and then heroku local, but get the 404 error.
Any help in the right direction would be great!
You're probably getting an exception when you start the node web server, due to a module dependency error.
Check your command/terminal window. If you see a red warning message pointing to your module.js file, you have an exception:
$ heroku local
forego | starting web.1 on port 5000
web.1 | module.js:341
In this case, you need to install the cool-ascii-faces module. In your 'node-js-getting-started' directory, use the following npm command to install:
$ npm i -S cool-ascii-faces
Also... you'll want to convert your index page route back to '/'. Your routes logic should look like this:
app.get('/', function(request, response) {
response.render('pages/index')
});
app.get('/cool', function(request, response) {
response.send(cool());
});
Otherwise, you'll always get the default 'pages/index' page when you hit the '/cool' route instead of a smiley face.
You don't have to include
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
}
Heroku will run "npm start" to start your server and dynamically choose the port. You don't have to specify port explicitly.
this problem happened for me. After I typed "git push heroku master", I typed "heroku open" and it worked.

Object #<MongoClient> has no method 'open'

I've been trying to make a simple site with Node.js, Express.js, and MongoDB. I'm new to these technologies and have been having problem set up the database
Here is snippet of code in my index.js file:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));
mongoClient.open(function(err, mongoClient) {
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1);
}
var db = mongoClient.db("MyDatabase");
collectionDriver = new CollectionDriver(db);
});
After I try to run node index.js in terminal, it says the following:
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/username/dev/ga-final/index.js:31
mongoClient.open(function(err, mongoClient) { //C
^
TypeError: Object #<MongoClient> has no method 'open'
at Object.<anonymous> (/Users/username/dev/ga-final/index.js:31:13)
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:906:3
What is wrong? Why can't I call open? Can you help me fix this? thanks!
This is happening may be because you are using new version of mongodb it is working fine after I use mongodb driver version 1.4.
npm install mongodb#1.4.x
Take a look at the mongodb docs. Your mongoClient object is not what you think it is, and that why there isn't an open() method available.
Make your example code look more like theirs:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});

Categories

Resources