Why is Middleware not working in express js - node.js

I am trying to learn middleware in express js. Could anyone help where I am missing? Here is my code
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use("/", function(req, res, next){
console.log("this is my second output");
next();
});
app.get('/', function(req,res){
console.log("this is my first output");
//res.send('Hello World');
});
app.listen(3000, function(){
console.log('Server started on port 3000...');
})
I am getting Server started on port 3000.. when I run on cmd and getting "page is not working" on localhost:3000
Edited
I got
Server started on port 3000...
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
after some time. But localhost:3000 is still not working

The reason you get the "page is not working" message is because your application does not respond to any request it receives.
You'll need to uncomment that res.send('Hello World'); in app.get('/', ...). After that your code works perfectly fine.
Note, however, that in the structure of your code, your middleware app.use(...) is called before you get to the main logic for the route (app.get(...)), contrary to what's indicated by your console.log calls.

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
// use this middleware to pass all the requests
app.use("/", function(req, res, next){
console.log("this is my second output");
// move to next middleware
next();
});
//handle all the get requests to localhost:3000 url
app.get('/', function(req,res){
console.log("this is my first output");
// send the response
res.send('Hello World');
// or you can send the response like this
// res.json(JSON.stringify({"success":"true"}));
});
app.listen(3000, function(){
console.log('Server started on port 3000...');
})
send a get request to http://localhost:3000

Mainly, Middlewares execution consists of two things: ->
next()
app.use()
const express = require('express');
const app = express();
const hola = function(req, res, next) {
console.log("are you okay?");
next();
console.log("Yes I'm okay....");
}
app.use(hola)
app.get('/',(req, res) => {
res.send('HEY SUDEEPA WELCOME TO OUR SERVER !!!
})
app.listen(3000,() => {
console.log('Server started at port 3000!!!! ');
})
In the above code if we do not mention the next() method in hola function then after clicking localhost:3000 our will got crashed because it is not getting it's next middleware which is our app.get. So, if we are not mentioning next() then it could be our one of reason for not getting executed Middlewares.

Related

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.

Is the express app object also an express middleware?

I just started learning express and I read that an express middleware is a Javascript function to handle HTTP requests. It accepts 3 parameters:- req, res and next.
When I tried the following code block:-
const express = require('express');
const app = express();
var x = app.get('/', function(req, res){
res.send('Hello World!');
} );
console.log(x.toString());
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
} );
I see the following output:-
function(req, res, next){
app.handle(req, res, next);
}
So is the express app object also an express middleware?
I'm sorry if this is a silly question, but wanted to have an insight nevertheless.
The .get() function is yes. the majority of the express functions .use() etc are really just middlewares for specific tasks. .get checks the req object against the url provided, if it's a match then it runs it's code. If it isn't then it continues to next() through all the other .get() middlewares.
The entire ecosystem of express is middlewares going to more middlewares

Rest Api with node.js localhost not answering

Hy there, I'm trying to learn to make a REST API. I have the following code, where I mention that i have no error. When I try to access localhost:3000 nothing happens it's just reloading a blank page. What am I doing wrong?
Servers.js
const http = require('http');
const app = require('./app').default;
const port = process.env.port || 3000;
const server = http.createServer();
server.listen(port);
App.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works!'
});
});
module.exports = app;
You've not defined any route. Express generator generates the boilerplate code which is use full to start with.
You can also define a route like this:
app.use('/', function (req, res, next) {
return res.render('index', {title: 'DASHBOARD', 'data': ''});
});
Have a look at this doc: https://expressjs.com/en/starter/generator.html

Rest Api routes only working for GET in production

I'm running a node.js rest api with Express v4. All the routes work as expected via localhost debug. But on my server, they don't. The only thing that differs, is that the port listening is done by Phusion Passenger on the server (I can't change that). Here's my app.js:
const express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
helmet = require('helmet'),
http = require('http');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(helmet());
app.use('/', require('./api/routes'));
var server = http.createServer(app);
var port = 'passenger'; // 3000 on localhost
server.listen(port, function () {
console.log('listening ' + port);
});
Here's a my routes.js that works on local debug, but won't on the server:
var express = require('express');
var router = express.Router();
router.get('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test get works !');
res.end('test get works!');
});
router.post('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test post works !');
res.end('test post works!');
});
module.exports = router;
Here are the logs for localhost (successful routing):
20180107_192254 | /api/test
20180107_192254 | { get: true }
20180107_192254 | test get works !
20180107_192350 | /api/test
20180107_192350 | { post: true }
20180107_192350 | test post works !
The log file of the same process, but done via the remote server (I'm always redirected to the first route, and req.method is always GET). While the 'req.route.path' is the always the good one, it never goes into the expected function:
20180107_192757 | /api/test
20180107_192757 | { get: true }
20180107_192757 | test get works !
20180107_192759 | /api/test
20180107_192759 | { get: true }
20180107_192759 | test get works !
Do you know if I have to update something somewhere (maybe .htaccess, or in the js code)? I couldn't find anything on both the Phusion and the Express doc.
EDIT:
I replace the express router with a direct use of route by the app and it doesn't work.
But I noticed something:
var express = require('express');
var router = express.Router();
router.get('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test get works !');
res.end('test get works!');
});
router.post('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test post works !');
res.end('test post works!');
});
router.get('/api/otherTest', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('other test get works !');
res.end('other test get works!');
});
module.exports = router;
Here, I can go the the first and the third routes. In fact, all GET routes work (and only them). If I do this:
var express = require('express');
var router = express.Router();
router.post('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test post works !');
res.end('test post works!');
});
module.exports = router;
I get nothing.
Ok. So I figure it out: my website is rerouting all http:// traffic to https:// traffic, and all requests (GET, POST, PUT,...) sent through http:// are somehow transformed to GET requests.
They are all correct via https://.
I don't know why this is happening, but feel free to give more details about this issue if you do! I'll update when I find out.

Basic express hello world

I have the following code in node.js which is very basic express code but I can't get it to work. when I visit localhost/, it gives me text "Cannot GET /". It should display Hello world.
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World!')
});
do you open port?
The server must open the port.
app.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send("Hello World");
});
app.listen(3000, function() {
console.log("server open");
});
If listen method called by app, Prepares to receive the client's response to the port passed as the first argument.
U can execute this code.
node app.js OR supervisor app.js OR forever start app.js ETC

Resources