1

I have written a code in NodeJS where when i hit the url, i need the server to pass through three middleware functions authentication, cookies, logging. Here it happens , but the console gets printed twice. Can you help me figure out why.

var express = require('express'); var app = express(); var router = require('express').Router(); /* Add the middleware to express app */ app.use (function authentication(req,res,next){ if(req.method === 'GET'){ console.log("Inside Authentication.js") next(); // If your don't use next(), the mmand won't go to the next function. } else{ console.log("Inside else Authentication.js") } }) app.use( function cookies(req,res,next){ if (req.method === 'GET'){ console.log("Inside cookies.js") next(); } else { console.log("Inside else cookies.js") } }) app.use( function logging(req,res,next){ if(req.method === 'GET'){ console.log("Inside Logging.js"); next(); } else{ console.log("Inside else of Logging.js"); } }) app.use(function(req,res) { res.send('Hello there !'); }); app.listen(8080); 

o/ p -

E:\NodeJSProject\middleware>node app.js Inside Authentication.js Inside cookies.js Inside Logging.js Inside Authentication.js Inside cookies.js Inside Logging.js 
2
  • Are you making two requests? :) If you're making a request through the browser to a different host and/or port your browser will do a pre-flight CORS request. Commented Mar 2, 2019 at 10:24
  • ok. I open and hit localhost:8080 in my browser. What to do to prevent pre-flight CORS request. Commented Mar 2, 2019 at 10:26

1 Answer 1

8

Your browser will perform a pre-flight CORS request (i.e. an OPTION request) to see whether you're allow to perform the request.

From your perspective its just one request, but the browser is performing two requests and your express server is executing both requests in full.

Given you're using express there is middleware available to handle those requests specifically.

See here for documentation.

If you want to avoid the CORS request altogether, your website and API need to be served from the same host, port, and protocol.

You can read more about CORS here, or you can search Stack -- theres extensive posts.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.