为什么console.log在Node.js中的app.js中出现两次 [英] Why does the console.log appear twice in app.js in nodejs

查看:43
本文介绍了为什么console.log在Node.js中的app.js中出现两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用NodeJS编写了一个代码,当我点击URL时,我需要服务器通过三个中间件功能验证,Cookie和日志记录.发生这种情况,但是控制台被打印了两次.你能帮我找出原因吗?

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

推荐答案

您的浏览器将执行飞行前CORS请求(即 OPTION 请求),以查看您是否被允许执行请求.

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

从您的角度来看,它只是一个请求,但是浏览器正在执行两个请求,而您的Express服务器正在完全执行两个请求.

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

鉴于您使用的是 express ,因此可以使用中间件专门处理这些请求.

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

请参阅此处获取文档.

如果您想完全避免CORS请求,则必须从相同的主机,端口和协议为您的网站和API提供服务.

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

您可以在此处阅读有关CORS的更多信息,或者可以搜索Stack-有大量帖子.

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

这篇关于为什么console.log在Node.js中的app.js中出现两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆