Why does the console.log appear twice in app.js in nodejs

我的未来我决定 提交于 2020-12-14 06:26:08

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/54957409/why-does-the-console-log-appear-twice-in-app-js-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!