【发布时间】:2021-12-07 02:44:46
【问题描述】:
这是我的代码最初的样子:
const express = require('express')
const app = express()
const morgan = require('morgan')
app.use(morgan('tiny'));
// app.use((req, res, next) => {
// console.log("OUR MIDDLEWARE")
// console.log(req.method.toUpperCase(), req.path);
// next();
// })
app.use((req, res, next) => {
console.log(req.query);
const { pwd } = req.query
if (pwd === 'chickennugget') {
next();
}
res.send("Sorry, you need a password")
})
app.get('/', (req, res) => {
res.send("HOME PAGE!!")
})
app.get('/dogs', (req, res) => {
res.send("WOOF WOOF!!")
})
app.listen(3000, () => {
console.log("App is running on localhost:3000")
})
它产生了这个错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/response.js:170:12)
at /Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/app.js:19:9
at Layer.handle [as handle_request] (/Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/router/index.js:317:13)
at /Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/router/index.js:335:12)
at next (/Users/tebahsaboun/Desktop/STUDIES/UDEMY/TWDB 2021/Section 40: Express/Middleware_Intro/node_modules/express/lib/router/index.js:275:10)
然后我本能地通过修改这段特定的代码来修复它:
app.use((req, res, next) => {
console.log(req.query);
const { pwd } = req.query
if (pwd === 'chickennugget') {
return next();
}
res.send("Sorry, you need a password")
})
(我在 next() 函数调用之前引入了一个 return。)
我的问题有两个:
- 为什么初始代码会出现此错误?
- 为什么要引入“return”关键字。修复错误?
我浏览了 StackOverFlow 以获得答案,并且有一个关于此错误的现有线程,但我看不出答案如何适用于我的特定情况。
非常感谢您的帮助。
最好的,
【问题讨论】:
标签: express middleware