Taking the following basic Express: 'Hello World' example as my starting point:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I'm trying to organize the code in different .js files to separate configuration and routing.
This way I would have app.js:
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
// Expose app
exports = module.exports = app;
and /routes/api.js (having api.js inside a child directory called routes):
var app = require('../app.js');
app.get('/', function (req, res) {
res.send('Hello World!');
});
but exports = module.exports = app; and var app = require('../app.js'); are not working: I get the message Cannot GET / all the time when calling the API method.
you should make app.js your 'main' file, and the routes should be inclulded in it.
your route file should look somthing like this:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
and to your app.js add:
var api = require("./routes/api.js");
...
//all your code for creating app
...
app.use('/', api);
Related
I have the following files
app.js
var express = require('express');
var app = express();
var api = require('./routes/api');
app.use('/api/v1/', api);
routes/api.js
var express = require('express');
var router = express.Router();
var users = require('./users');
router.get('/Users', users);
module.exports = router;
routes/users.js
var express = require('express');
var router = express.Router();
router.get('/')
.get(function(req, res) {
res.send('Hello world');
});
module.exports = router;
Why doesn't this work?
I think you should customise this by using separate routes file.
app.js
var express = require('express'),
app = express(),
routes = require('./routes'); // Create a routes folder and under that create index.js
app.use('/', routes);
routes/index.js
var express = require('express'),
router = express.Router(),
apis = require('apis');
router.get('YOUR API NAME', apis.api);
router.post('YOUR API NAME', apis.ANOTHER API HERE);
Create a folder apis and put your API under apis folder also create a index.js for exporting your APIs.
apis/index.js
var APIs = ['api', 'ADD MORE APIs here'];
APIs.forEach(function(api) {
module.exports[api] = require(__dirname + '/' + api)[api];
});
hope this will help you : )
In routes/users.js
Instead of
router.get('/')
.get(function(req, res) {
res.send('Hello world');
});
Try
router.get('/',function(req, res) {
res.send('Hello world');
});
Or
router.route('/')
.get(function(req, res) {
res.send('Hello world');
});
Using router.use instead of router.get in api.js fixed it for me
I have this router (http/api/ping.js):
var express = require('express');
var router = express.Router();
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
module.exports = router;
This router is embedded into this router (http/api/index.js):
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('You called /api');
});
router.use('/ping', require('./ping'));
module.exports = router;
And this router is used by my Express.js app (app.js):
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;
// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);
// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));
// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});
module.exports = {
app: app,
server: server
};
When I run the app, /api returns You called /api, but /api/ping gives me a 404.
I am using Node 6.9.1 and Express ^4.14.0
I think order matters in this scenario. Try putting /ping above the / get route.
router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
res.send('You called /api');
});
Also in your ping route you say the path to your route is /ping you also say it is /ping when you import it to the other router, which would make the path /api/ping/ping
change
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
to
router.get('/', function (req, res) {
res.send("You called /api/ping");
});
I think your routing is incorrect on this line
router.use('/ping', require('./ping'));
this will point to http/api/ping/ping
it should be
router.use('/', require('./ping'));
This below code is my first Express restfull application. After running server.js I expected after entering http://localhost:3020/helloworld url on FireFox I get Hello, World! message, but I get this message:
Cannot GET /helloworld
code:
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3020;
/* GET home page. */
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' });
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
You are defining the route on the router, not on the app.
var router = express.Router();
is a router, different than app.
var app = express();
What you are doing wrong, is you are not mounting the router on the app where the /helloworld route is defined.
do either of the following:
app.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' });
});
Or else add the following line in your app:
app.use('/',router);
How start app in express js (nodejs)? TypeError:app.set is not a function.
Console.log screen
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
});
Solved a problem:
1. add module.exports = app;
I have this code:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
I will have many services (like the test one), and I don't want to have them all on the same file.
I read in another question in Stack Overflow, that I can require other files like this: var express = require("./model/services.js"); And in that file write all the services, but it's throwing app is not defined when I start Node.
How can I separate codes?
You can define your routes in different files say test-routes.js like this:
module.exports = function (app) {
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
}
Now in your main file say server.js you can import your route file like this:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
// import your routes
require('./test-routes.js')(app);
your test.js should look something like:
var express = require('express');
var router = express.Router();
router.get('/test', function (req, res) {
res.json(200, {'test': 'it works!'});
});
module.exports = router;
and the app.js (assuming other is some other route defined similarly to test.js):
var test = require("./routes/test.js");
var other = require("./routes/other.js");
...
//all your code for creating app
...
app.use('/test', test);
app.use('/other', other);