Nodejs Cannot GET /helloworld in simple application - javascript

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);

Related

koa.js basic app always returns Not Found

I'm trying to write my first ever koa.js app, and for some reason I just can't set a route with a function. I keep getting a "Not Found" error.
Here's my code -
const koa = require('koa'),
router = require('koa-router')();
var app = new koa();
router.get('/', function *(next) {
this.body = "Hello"
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
console.log("Listening on port 3000");
This code is based on the koa-router github example
Then when I go to localhost:3000 I get "Not Found"
What am I missing?
Thanks
Now function generator is deprecate in koa2. Used code like
const koa = require('koa'),
router = require('koa-router')();
var app = new koa();
router.get('/', function(ctx, next) {
ctx.body = "Hello"
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
console.log("Listening on port 3000");
I've been getting the same error but i found out that maybe this is the easiest way of doing it.
'strict'
const koa = require('koa')
const app =new koa()
var route = require('koa-router');
const host = 'localhost' || '127.0.0.1';
const port = 3123 || process.env.PORT;
// initiate the route
var my_route = route();
// defines the route
my_route.get('/',function(body, next){
body.body = "I love routes"
});
app.use(my_route.routes())
app.listen(port, host,(err)=>{
if(err){
throw err;
}
console.log("The server has started")
})
I know this is old but for anyone who is new in koa, and beside using the new way in koa 3, as i had same error because lot of documents and examples just confuse me, it is said that routes should be last middleare to use but not before settings routes so you should write the line of using routes middlware before the code setter of routes like that:
const koa = require('koa'),
router = require('koa-router')();
var app = new koa();
app.use(router.routes())
.use(router.allowedMethods());
router.get('/', function *(next) {
this.body = "Hello"
});
app.listen(3000);
console.log("Listening on port 3000");

Getting Port Number at which NodeJS server is listening

I am trying to retrieve the port number on which NodeJS is listening on. Currently I saving the port number value in app.js variable and trying to access it in index.js file. However, I am getting undefined value in index.js file. I am not sure why is this happening. How can I fix this?
index.js
var express = require('express');
var app = require('../app');
var router = express.Router();
var socket = require('socket.io');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
console.log("port: "+ app.portNumber);
socket.listen(app.portNumber);
});
module.exports = router;
app.js:
var portNumber;
// rest of the controller code which calls the correct routes when a webpage is requested.
www.js:
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
app.portNumber = port;
This will export the variable port and will be available whenever you
import it var app = require('../app');
app.js:
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
app.portNumber = port;
exports = module.exports = {
portNumber : port
}
index.js:
var app = require('../app');
console.log("port: "+ app.portNumber);

How start app in express js (nodejs)? TypeError:app.set is not a function

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;

Exporting and requiring Express application issue

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);

Modularizing Socket.io with Express 4

I'm trying to modularize my application files and I'm having problems with Socket.io. I would like to use the io inside my routes.js. Something like this:
var router = require('express').Router();
var io = require('./sockets/my-io');
router.get('/', function(req, res) {
io.emit('request-detected');
});
module.exports = router;
But I can't do, because the socket.io needs the app server, and when I'm inside the routes.js file, the app server is not listening or being exported yet.
Can you give me a solution, or any other approach to this problem?
Here's what I have, and if it's possible, I would like to keep the file structure:
app.js
var app = require('express')();
var routes = require('./routes');
/* ... */
app.use('/contacts', routes);
module.exports = app;
bin/www
#!/usr/bin/env node
var app = require('../wallet');
var server = app.listen(port, function() {
debug('Express is listening o port ' + port);
});
routes.js
var router = require('express').Router();
router.get('/', function(req, res) {
console.log('hey');
});
module.exports = router;
You can do it by passing the io variable to your routes module.
bin/www
#!/usr/bin/env node
var app = require('./app');
var server = app.listen(3000, function() {
console.log('Express is listening on port 3000');
}); // start the server
var socket = require('./socket')(server); // require socket.io code
var routes = require('./routes')(socket); // require routes
app.use('/', routes);
app.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('views engine', 'ejs');
app.set('views', __dirname + '/');
module.exports = app;
socket.js
var socketio = require('socket.io');
function init(server) {
var io = socketio(server);
io.on('connection', function (socket) {
console.log("socket connected");
socket.on('newEvent', function (data) {
console.log(data);
});
});
return io;
}
module.exports = init;
routes.js
var express = require('express');
var route = express.Router();
function init(io) {
route.get('/', function (req, res) {
res.render('index.ejs', {});
setTimeout(function() {io.emit('newEvent', {message: "Hi from the server"})}, 2000);
});
return route;
}
module.exports = init;
The code above worked for me. However, I'm not sure why you want to do that.
Inside the router, you still have full control of what you want to send to the user via html, so you can just add the data to the html directly.
The idea of socket.io is that you can send data between the client and back once he has loaded the html and established a connection to your server with socket.io.
As you can see in the routes.js, I had to add a timeout to the emit. This is because the socket event will be emit before the browser has reloaded the page. In my case the browser logged the event and then immediately refreshed, losing the data you just sent.
Another problem is that you don't know anything about the socket of the client that is requesting the page because he hasn't connected yet. This means that calling io.emit() will send the event to all connected sockets.
As I said, this really depends on what exactly you want to do.
EDIT:
Instead of updating your contacts using ajax, you can do that with socket.io.
socket.js
var socketio = require('socket.io');
function init(server) {
var io = socketio(server);
io.on('connection', function (socket) {
console.log("socket connected");
socket.on('newContact', function (data, callback) {
// add data.contactName to db
// after adding something, you use the callback to
// send the added data back to the client
// callback(newContact);
});
});
return io;
}
module.exports = init;
index.html
<script type="text/javascript" >
var socket = io();
// call this emit when the user wants to add a contact
socket.emit('newContact', {contactName: name}, function(newContact) {
// here you will get the result from the server and you can
// update the html with jquery for example
});
</script>
If i understand your question correctly ,maybe you can try this way.
in your routes.js file
var app = require('./app');
var server = require('http').createServer(app);
var io = require('./sockets/my-io')(server);
var route = app.Router();
in your app.js file
var port = process.env.PORT || 3000;
app.listen(port,function(){
console.log('server on port ' + port)
})

Categories

Resources