【问题标题】:Why does the console.log appear twice in app.js in nodejs为什么console.log在nodejs的app.js中出现两次
【发布时间】:2019-07-24 05:46:34
【问题描述】:

我在 NodeJS 中编写了一个代码,当我点击 url 时,我需要服务器通过三个中间件功能身份验证、cookies、日志记录。在这里它发生了,但是控制台被打印了两次。你能帮我找出原因吗?

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 请求。
  • 好的。我在浏览器中打开并点击 localhost:8080。如何防止飞行前 CORS 请求。

标签: node.js express server


【解决方案1】:

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

从您的角度来看,它只是一个请求,但浏览器正在执行两个请求,而您的快速服务器正在完整执行这两个请求。

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

See here for documentation.

如果您想完全避免 CORS 请求,您的网站和 API 需要从相同的主机、端口和协议提供服务。

You can read more about CORS here,或者你可以搜索 Stack -- 这里有很多帖子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多