Node app route is not working - javascript

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!

Related

Node.js Express module exports

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

Node Js express router not working

js and i am learning node js along with express and I was learning express routing I have following code in rest.js
const http = require('http');
const express = require('express');
const widgetRouter = require('./rest/widgets');
const app1 = express();
const server = http.createServer(app1);
app1.get('/api',widgetRouter);
server.listen(3000,function(){
console.log('server started in port 3000');
});
const app = express();
and I also have widgets.js file
const express = require('express');
const widgetRouter = express.Router();
widgetRouter.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
widgetRouter.route("/widgets/:widgetId")
.get()
.put()
.delete();
module.exports = widgetRouter;
but When I try to test the rest api(http://localhost:3000/api/widgets) from postman it says Cannot GET /api/widgets
You have imported and initialized the express module, but then you start a server with the http module. You should use only Express:
Also you should use app.use('/api',widgetRouter) instead of app.get('/api', widgetRouter) which is an express middleware.
const express = require('express');
const app = express();
const widgetRouter = require('./rest/widgets');
app.use('/api', widgetRouter);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000, function(){
console.log('server started in port 3000');
});
You can also try that.
rest.js
const express = require('express');
const http = require('http');
const router = express.Router();
const app = express();
require('./widgets')(app, router);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000,function(){
console.log('server started in port 3000');
});
widgets.js
module.exports = function(app, router){
router.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
router.route("/widgets/:widgetId")
.get()
.put()
.delete();
app.use('/api', router);
});

Node + Express JS API is not working

I'm a beginner in node.js but I try a little harder to setup a structure in node + express js.I start doing with the front-end and separate API structure.I put a single app.js for both API and front-end.But my API is not working. it gives error Cannot GET /api/users when i call http://localhost:3000/api/users. please help
api
-controllers
-helpers
-middlewares
-models
-routes.js
app.js
controllers
helpers
middlewares
models
node_modules
package.json
public
views
app.js
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000
var path = require('path');
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(require('./controllers'))
var routes = require('./api/routes');
app.use('/api', routes);
app.listen(port, function() {
console.log('Listening on port ' + port)
})
routes.js
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
module.exports = function (app) {
app.get('/users', usersController.getUser);
};
module.exports = router;
users.js(controller)
module.exports = {
getUser: function (req, res) {
console.log("sdfdsfdsfsd");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({"msg": "welcome user"}));
}
}
In your routes.js file you are exporting two things. Try to only export the router
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
router.get('/users', usersController.getUser);
module.exports = router;

Express routing error Cannot Get /api/name

Having some trouble setting up the restful API for my express app.
Here is my app.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override');
routes = require('./routes'),
api = require('./routes/api'),
port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(bodyParser.urlencoded({extended: true}));
// Page Routes
app.get('/', routes.index);
app.get('/partials/:filename', routes.partials);
// // API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
In /routes/api.js I have the following test function:
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
Currently I get the following error when i go to http://my_ip/api/name
Cannot GET /api/name
Any ideas?
Thanks
The following code is working for me. I think there is some issue with your routes package. Can you share the code of 'routes' package and file structure ?
app.js
var express = require('express'),
app = express(),
routes = require('./routes');
api = require('./routes/api'),
port = process.env.PORT || 3000;
// Page Routes
app.get('/', routes.index);
// API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
/routes/api.js
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
/routes.js
exports.index = function (req, res) {
res.json({
name: 'Index'
});
};

How to get my node.js mocha test running?

I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this:
mocha test
I could not figure out how to get the reference to my app, routes.js:
var _ = require('underscore');
module.exports = function (app) {
app.post('/*', function (req, res) {
var schema={
type: Object,
"schema":
{
"totalRecords": {type:Number}
}
};
var isvalid = require('isvalid');
var validJson=true;
isvalid(req.body,schema
, function(err, validObj) {
if (!validObj) {
validJson = false;
}
handleRequest(validJson,res,err,req);
});
})
}
This is the server.js:
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
And finally test.js:
"use strict";
var request = require('supertest');
var assert = require('assert');
var express = require('express');
var app = express();
describe('testing filter', function() {
it('should return an error', function (done) {
request(app)
.post('/')
.send({"hh":"ss"})
.expect(400,{"error": "errormsg"})
.end(function (err, res) {
if (err) {
done(err);
} else {
done();
}
});
});
});
Create a separate file called app.js. The only purpose of this file would be to run the server. You'll also need to export your app object from server.js. So, your server.js would look like this
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
module.exports = app;
Create a new file called app.js and put this inside of it
var app = require('./app');
var port = process.env.port || 8000;
app.listen(port, function() {
console.log("App listening on port " + port);
});
Now, inside of your test file, import your app as follows
var request = require('supertest');
var assert = require('assert');
var app = require('./app.js');
....
Note that I assume all your files are in the same directory. If you've put your test file in a different folder then you'll need to give the right path while requiring your app object.

Categories