Suc*_*ava 1 node.js express server
我在 NodeJS 中编写了一个代码,当我点击 url 时,我需要服务器通过三个中间件函数身份验证、cookie、日志记录。在这里它发生了,但控制台打印了两次。你能帮我弄清楚原因吗。
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);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
您的浏览器将执行飞行前 CORS 请求(即OPTION
请求)以查看您是否被允许执行该请求。
从您的角度来看,它只是一个请求,但浏览器正在执行两个请求,而您的快速服务器正在完整地执行这两个请求。
鉴于您使用的express
是中间件,可以专门处理这些请求。
如果您想完全避免 CORS 请求,您的网站和 API 需要从相同的主机、端口和协议提供服务。
您可以在此处阅读有关 CORS 的更多信息,或者您可以搜索 Stack —— 那里有大量帖子。
归档时间: |
|
查看次数: |
1275 次 |
最近记录: |