表示当浏览器发出请求时两次调用的中间件函数 [英] express middleware functions invoked twice when request is made from browser
本文介绍了表示当浏览器发出请求时两次调用的中间件函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的nodejs代码
Below is my nodejs code
const express = require('express');
const app = express();
app.use('/', (req, res, next) => {
console.log("In interceptor");
next();
});
app.use('/users', (req, res, next) => {
console.log('In /users middleware');
res.send('<h1>From "/users" handler </h1>');
});
app.use('/', (req, res, next) => {
console.log("Default handler");
res.send('<h1>From default handler</h1>');
});
app.listen(3000);
从浏览器(Chrome和Edge)发出请求时控制台输出
Console output when a request is made from browser (both chrome and edge)
http://localhost:3000
******************
In interceptor
Default handler
In interceptor
Default handler
******************
http://localhost:3000/users
******************
In interceptor
In /users middleware
In interceptor
Default handler
******************
但是当使用curl
发出请求时,我看不到多次调用
But when a request is made using curl
, I don't see multiple invocations
curl http://localhost:3000
******************
In interceptor
Default handler
******************
curl http://localhost:3000/users
******************
In interceptor
In /users middleware
******************
有人可以解释为什么从浏览器发出请求时多次调用中间件功能吗?
Can someone explain why middleware functions are invoked multiple times when request is made from browser?
推荐答案
从浏览器加载页面时看到多个请求的常见原因是两件事之一:
The usual reasons you see multiple requests when a page loads from a browser are one of two things:
- 浏览器自动请求favicon.ico文件.
- 浏览器尝试从HTML文件(脚本文件,图像,CSS文件等)中加载某些资源
通过添加以下内容,您可以确切地看到每个请求的目的:
You can see exactly what each request is for by adding:
console.log(req.url);
到您的中间件.
这篇关于表示当浏览器发出请求时两次调用的中间件函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文