我正在编写非常基本的快速代码
const express = require('express');
const app = express();
app.use('/willgo', (req, res, next) => {
console.log('In a middleware');
next();
})
app.use('/notgo', (req, res, next) => {
console.log('In another middleware');
res.send('<h1> Inn intermediate </h1>');
res.end();
})
app.use('/', (req, res, next) => {
console.log('In final middleware');
res.send('<h1> Inn final </h1>');
})
// const server = http.createServer((req, res) => {
// server.listen(2001);
app.listen(3002);
在本地主机上:3002/notgo
控制台是
In another middleware
In final middleware
它显示最后一个中间件已执行,即使我已经发送了请求。
这是最糟糕的行为还是我错过了一些东西,因为 res.send() 应该完成处理。
圈
res.end();
将完成响应。但是,此代码是否需要是中间件或普通endpoint?
然后你应该使用 app.get();
控制台输出“在最终中间件中”可能是因为浏览器想要从根目录加载一个favicon.ico,这将调用app.use('/',...)
如果您从 cli 执行 curl / 调用 Web 请求,您将看到只有一个控制台输出。
在 Windows 10/11 上:(IWR http://localhost:3002/notgo).content