【发布时间】: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 请求。