im getting this error
app.get is not a function
this is my config/express.js
var express = require('express');
module.exports = function(){
var app = express();
app.set('port',3000);
return app;
};
and this is my server.js
var http = require ('http');
var app = require ('./config/express');
http.createServer(app).listen(app.get('port'), function(){
console.log("Express Server Runing on port"+ app.get('port'));
});
what im doing wrong?
in config/express.js you export a function but use it as an app. Try this instead:
var express = require('express');
var app = express();
app.set('port', 3000);
module.exports = app;
Edit: But the following is preferred:
/* config/express.js */
var express = require('express');
module.exports = function() {
var app = express();
app.set('port', 3000);
return app;
};
/* server.js */
var http = require('http');
var app = require('./config/express')(); // Notice the additional () here
http.createServer(app).listen(app.get('port'), function() {
console.log("Express Server Runing on port"+ app.get('port'));
});
Whenever you use Nodejs and express js or anyother first check your Versions . that can save a lot of time . Like if you move from express 3 to express 4 so you better check versions
Related
I am starting to build a mean stack appliction, and when I run my app with the command:
npm app.js I get this:
error:TypeError: cars is not a function
I'm install all the relevant modules with the command:npm install #type,
This is my code:
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var cars = require('cars');
var bodyparser = require('body-parser');
var path = require('path');
var app =express();
const route = require('./routes/route');
//port number
const port=3000;
//adding middleware - cars
app.use(cars());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
//routes
app.use('/api',route);
//testing server
app.get('/',(req,res)=>{
res.send('Welcome to port 3000!');
});
app.listen(port,()=>{
console.log('server started at port:'+ port)
});
i dont know what i need to do,its seems that i have a problem with the cars modules,please help me,thank you!
Working with express Router for getting for the first time.
This is my route.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('home page');
});
module.exports = router;
This is my index.js
var express = require('express');
var app = express();
var router=require('./route.js');
app.use('/route',router);
var server = app.listen(process.env.PORT ||8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});
When I open run it in browser it shows:
Cannot GET /
The only URL the code you have written will respond to is:
www.example.com/route/
If you want it to respond to:
www.example.com
then change to the following in your index.js file:
app.use('/', router);
You should replace
app.use('/route',router); with app.use('/', router);
As I may see you have created default route in app.use as /route
you must not have added that using app.use('/') would be enough instead of creating another route for that
Thanks.
Question is how to pass variable to other js file in the simplest way (without any routes just with module.exports).
My file structure looks like this (very simple popular structure):
ROUTES (folder)
--form.js
--test.js
VIEWS (folder)
--form.ejs
--test.ejs
index.js
package.json
index.js file (standard express app file):
var express = require('express');
var body_parser = require('body-parser');
var form = require('./routes/form.js');
var test = require('./routes/test.js');
var app = express();
app.set('view engine', 'ejs');
app.use(body_parser.urlencoded({extended:true}));
app.use('/', form);
app.use('/test', test);
var port = 3700;
var server_listen_on = app.listen(port, function()
{
console.log('Server is listening on port: ' + port);
});
form.js file:
var express = require('express');
var body_parser = require('body-parser');
var router = express.Router();
var preciousData = 'var precious_data - from form.js file';
module.exports =
{
exportsPreciousData : preciousData,
router : router
};
test.js file:
var express = require('express');
var request = require('request');
var router = express.Router();
var requireFormjs = require('./form.js');//({exportsPreciousData : exportsPreciousData});
//console.log(requireFormjs.exportsPreciousData); // I guess console.log is faster then module.exports... but
router.get('/', function(req, res, next)
{
res.render('welcome', {test : requireFormjs.exportsPreciousData});
});
// why this doesn't work - I need to use middleware function - could you provide simple working example?
//(I guessing that even if console.log print data after module.exports machinery I would still need middleware, right?)
module.exports = router;
welcome.ejs file:
<!DOCTYPE html>
<html>
<head>
<title>welcome</title>
</head>
<body>
<%= test %>
</body>
</html>
... why it's not working (without express everything runs fine)?
Simple make those other files return a function:
Test.js:
module.exports = function(preciousData) {
// do everything here
return router;
}
index.js:
var test = require('test.js')(preciousData);
Data is passed by calling the function that test.js returns and router is returned from that function
currently developing a distributed system and crashed my code last night. My server-application has multiple modules which each established a connection to my redis db, however it would be better if there is a single connection via the main module. This, I tried to implement last night, But I can't quite figure out what exactly is the problem. I'm still quite new to this field, and already searched through pages like SitePoint, Medium, and other blogs, and also checked for my problem or derived versions of it here, but found nothing what could help me enough to settle this.
UPDATE 2016/6/24 13:18
I removed the app.use()-Statement from my code and now the server is firing up. Progress :)
However, If I try to test a route , the only reply I get is Cannot <METHOD> <ROUTE>.
Looking at this question here provides me with the answer to utilize the very app.use() I just removed from the code. Is there something I'm missing?
UPDATE 2016/6/24 14:05
I implemented the statement app.use('/', account_routing.routes);, doesn't work but seems the right way to go, doesn't it? I can send requests, but there is no answer whatsoever right now.
I'm providing the code for my server application:
main.js
var
express = require('express'),
redis = require('redis'),
app = express(),
port = process.env.port || 3000,
rclient = redis.createClient(),
account_routing = require('./modules/account_routing');
// ### CONFIGURATION ################################################
rclient.on('connect', function (err, res) {
console.log(err || "Connected to database!");
});
account_routing.setClient(rclient);
app.use('/', account_routing.routes);
// ### FIREUP #######################################################
app.listen(port, function () {
console.log('Server available at port ' + port);
});
account_routing.js
var rclient, express;
express = require('express');
module.exports = {
setClient : function (inClient) { 'use strict'; rclient = inClient; },
routes : function(app) {
// ### VARIABLES ####################################################
var bodyParser, http, morgan, redis, rclient, app;
// ### DEPENDENCIES #################################################
bodyParser = require('body-parser');
http = require('http');
morgan = require('morgan');
redis = require('redis');
app = express();
// ### CONFIGURATION ################################################
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// ### ROUTES #######################################################
app.get('/users/:username', function (req, res) {
/* Access database via connection in main module
to retrieve user data */
});
}
};
Thank you all very much in advance for help.
So basically after an awful lot of lost nerves, I stumbled upon this nice gem here.
I implemented it this very way, so now I have:
main.js
"use strict";
var
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
port = process.env.port || 3000,
account_routing = require('./modules/account_routing')(app);
app.listen(port, function () {
console.log('Server available at port ' + port);
});
redis_db.js
var
redis = require('redis'),
rclient = redis.createClient();
rclient.on('connect', function (err, response) {
'use strict';
console.log("Connected to database");
});
module.exports = rclient;
and account_routing.js
'use strict';
module.exports = function (app) {
var
bodyParser = require('body-parser'),
http = require('http'),
morgan = require('morgan'),
rclient = require('./redis_db');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(morgan('dev'));
/* Routes */
This way, there is a single connection established to the redis database, and also the routes are working properly now.
I hope this information will help somebody.
Im fairly new to node JS and I've created the following 3 files and when save the application I got error
http.createServer(app).listen(**app.get('port')**, function(){
the error is undefined is not a function
I use nodemon and I see the error in the terminal
I want to keep the structure of the files(to initiate the server from different file - server.js )since I want to use TDD .
this is the files
server.js
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'));
});
app.js
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
app.use(require('./controllers/requests'));
return app;
}
requests.js
var routers = require('express')
, router = express.Router()
router.get('/wild', function(req, res) {
debugger;
res.send('Wolf, Fox, Eagle')
})
module.exports = router
UPDATE
This is the update in the code
app.js
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
app.use(function(){
var routes = require('./controllers/requests') (app);
});
return app;
}
requests.js
**
module.exports = function (app) {
var express = require('express')
, router = express.Router();
app.get('/wild', function(req, res) {
res.send('Wolf, Fox, Eagle');
})
}
server.js
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'));
});**
You should invoke the function returned by module containing app.
app = require('./app') ();
Moreover, in request.js file you should define routes on your app instance:
module.exports = function (app) {
app.get('/wild', function(req, res) {
res.send('Wolf, Fox, Eagle');
})
}
And in app.js:
app.use(function () {}) is used to define middlewares. Here you could call
var routes = require('./controllers/requests') (app);
EDIT
Please find here below the recap to answer your comments:
server.js
var http = require('http');
var app = require('./app') ();
http.createServer(app).listen(app.get('port'), function(err){
console.log('Express server listening on port ' + app.get('port'));
});
app.js
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
require('./controllers/requests')(app);
return app;
}
requests.js
module.exports = function (app) {
app.get('/wild', function(req, res) {
res.send('Wolf, Fox, Eagle')
});
}
Hope this helps!