Not able to solve Express Middleware issue - node.js

My first piece of code below:
var express = require('express');
var app = express.createServer(express.logger());
app.get('/', function(request, response){
response.send('Hello World 2');
});
var port = process.env.PORT || 5000;
app.listen(port, function(){
console.log("Listening on " + port);
});
Threw up the error: "Most middleware (like logger) is no longer bundled with Express and must be installed separately"
So I looked at StackOverflow, did npm install morgan, and changed my code to:
var express = require('express');
var logger = require('morgan');
var app = express.createServer(logger());
app.get('/', function(request, response){
response.send('Hello World 2');
});
var port = process.env.PORT || 5000;
app.listen(port, function(){
console.log("Listening on " + port);
});
Now I get this error:
var app = express.createServer(logger());
^
TypeError: Object function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, proto);
mixin(app, EventEmitter.prototype);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
} has no method 'createServer'

That is because createServer method has been removed from express.
use
app = express();
app.use(logger())
instead of
app = express.createServer(logger())
Many things got changed from express 3.0 to 4.0. You should have a look here

You should create app with express(). Afterwards, you can setup any middleware (like morgan in this case) with app.use:
var express = require('express');
var logger = require('morgan');
var app = express();
app.use(logger());
...
app.use() documentation: http://expressjs.com/4x/api.html#app.use. (Linking to Express 4.x documentation as not explicit what Express version you're running).
There is an exact same example like the one I wrote above in Morgan's README in GitHub.

Related

Issue to add socketio to API Express

i'm trying to add socket.io on my already existing NodeJS API REST Project.
var express = require('express')
var bodyParser = require('body-parser');
var https = require('https');
var http = require('http');
var fs = require('fs');
var router = require('./route/router');
require('dotenv').config();
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(require('helmet')());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization,Content-Type');
next();
});
router(app);
if (process.env.PRODUCTION === "false") {
http.createServer(app).listen(8080, function() {
console.log('8080 ok');
});
var io = require('socket.io')(http);
} else {
const options = {
cert: fs.readFileSync('./../../etc/letsencrypt/live/test.com/fullchain.pem'),
key: fs.readFileSync('./../../etc/letsencrypt/live/test.com/privkey.pem')
};
https.createServer(options, app).listen(8443, function() {
console.log('8443 ok');
});
var io = require('socket.io')(https);
}
io.sockets.on('connection', socket => {
console.log('socketio connected');
});
I have no error displayed (server side). But, when I tried on client side, this.socket = io('ws://localhost:8080/');, it's not working at all.
I get GEThttp://localhost:8080/socket.io/?EIO=3&transport=polling&t=NG6_U6i [HTTP/1.1 404 Not Found 1ms] browser console.
It seems that something is not ok with the server, but I can't find what's going on
Any idea ?
Thanks
Try this way, you need to include (I don't know if this is the correct word to use) the express server into the socket.io server.
const express = require('express');
const socketio = require('socket.io');
const port = process.env.PORT || 3006;
const app = express();
const server = app.listen(port, () => {
console.log(`App started on port ${port}`)
});
const io = socketio(server, { forceNew: true });
io.on('connect', (socket) => {
// do this
// do that
});
The code above is a skeleton of how express and socket.io are used together. Please modify it as per your needs.
Good luck.

Why is DEBUG not logging in the console?

I am trying to take a tutorial on node.js and express. I'm trying to use the debug feature, but it is not logging anything to the console.
console.log works fine...but using debug() does not
I am on windows and am trying to run the app with...
set DEBUG=app ; node app.js
var express = require('express');
var chalk = require('chalk');
var debug = require('debug')('app');
var app = express();
app.get('/', function(req, res){
res.send('Hello from my library app');
})
app.listen(3000, function(){
debug(`listening on port ${chalk.blue('3000')}`);
});
Try this:
var express = require('express');
var chalk = require('chalk');
var app = express();
var debug = require('debug')(app);
app.get('/', function(req, res){
res.send('Hello from my library app');
})
app.listen(3000, function(){
debug(`listening on port ${chalk.blue('3000')}`);
});

Why content of middleware is running four times on single request from browser

Why does console.log('First Log') run 4 times per request?
//app.js
const express = require('express');
var app = express();
app.use((req, res, next) => {
console.log('First Log'); // problem is here
next();
});
app.use((req, res, next) => {
res.send('first response from express');
});
module.exports = app;
//server.js
const http = require('http');
const app = require('./backend/app');
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Output:
First Log
First Log
First Log
First Log
Middleware can be generic to all paths, or triggered only on specific path(s) your server handles. Below is an example of middleware declaration.
var app = express();
app.use(function () {}) //added to all paths or globally
app.get('/someroute', function() {}) //added to a specific path
Ref:
https://medium.com/#agoiabeladeyemi/a-simple-explanation-of-express-middleware-c68ea839f498
Answer mentioned in the comment by #AikonMogwai is also correct:
The middleware works one time for each url(of the same route path): index.html, favicon.ico, *.css, etc.
Change console.log to console.log(req.url) to see that.

Node.js code does not execute

I have written some Node.js code but when I run node index.js in my terminal it's just blank. My Node script does not even log to the console after creating the server or is responding with my index.html file. I even tried changing all 'req' and 'res' to 'request' and 'response'. Here's my code:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({ extended: false });
http.createServer(function(request, response){
console.log('listening on port 8080');
app.on('request', function(request, response){
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function(request, response){
var user = request.body.user;
var pass = request.body.pass;
});
}).listen(8080);
Pleas help. Thanks in advance.
EDIT: Anything inside the http.createserver(); does not execute because I tried logging another sentence outside the http.createServer(); and it logged!
Go ahead and try the following:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({extended: false});
app.on('request', function (request, response) {
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function (request, response) {
var user = request.body.user;
var pass = request.body.pass;
});
// Bind createServer with app:
http.createServer(app).listen(8080, function (request, response) {
console.log('listening on port 8080');
});
I expect that this should work for you.
Update:
The method mentioned, while works, has become outdated.
the recommended method is:
app.listen(8080, function () {
console.log('listening on port 8080');
});
Using this method allows you to skip requiring http.

Multiple node apps in sub folders

I want to create a site with this structure:
--mysite.com
--mainserver.js
-----mysite.com/project1
-----server.js
-----mysite.com/project2
-----server.js
In each project folder I want to run a separate node application. Im trying to do this using vhost module.
In my mainserver.js I have this to test:
var express = require("express");
var app = express();
var router = express.Router();
var vhost = require('vhost');
var app2 = express();
app2.get('/', function(req, res) {
res.send("echo");
});
app.use(vhost('localhost/project1', app2));
app.get('/', function(req, res) {
res.send("hi");
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
//console.log("Listening on " + port);
});
When navigating to localhost:8000 I see the "hi". But when I navigate to localhost:8000/project1 I get Cannot GET /test...
Please help!
I believe this is what you are trying to achieve. (Without use of vhost)
project1/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
return res.send('project 1');
});
// Other routes specific to project 1 here
module.exports = router;
Project2 could be set up similarly.
server.js
var express = require('express');
var app = express();
app.use('/project1', require('./project1'));
app.use('/project2', require('./project2'));
var port = Number(process.env.PORT || 5000);
app.listen(port);

Resources