使用next()和res.send.在将标头发送到客户端后无法设置标头.错误[ERR_HTTP_HEADERS_SENT



我是node js的新手,表达并学习basicss,,在我看到的其他代码错误中,我曾经通过看到throws部分进行调试,但它在这里。。

编辑:我是中间件概念的新手;next((,这已经创建了在投票支持的答案中看到的错误。

代码:

const express = require('express')
const app = express()
app.use('/add-product',(req,res,next)=>{
console.log("This is add-product page")
res.send("<form action='/product' method ='POST'><input type='text' name ='title'><button type ='submit'>Submit</button></form> ")
next()
})
app.use('/product',(req,res,next)=>{
console.log('this is product-page')
res.redirect('/')
})
app.use('/', (req,res,next)=>{
res.send('Welcome to NodeJS')
})
app.listen(3000)

错误:

[nodemon] starting `node app.js`
This is add-product page
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.contentType (C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibresponse.js:624:15)
at ServerResponse.send (C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibresponse.js:149:14)
at C:UsersADesktopvs codethe complete tutorialapp.js:14:9
at Layer.handle [as handle_request] (C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibrouterindex.js:328:13)
at C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibrouterindex.js:286:9
at Function.process_params (C:UsersADesktopvs codethe complete tutorialnode_modulesexpresslibrouterindex.js:346:12)

当您处理完请求并为其获取数据以及发送最终响应时,请在res.send 之前使用return

您面临的上述错误是因为您在'/add-product'中调用的next()函数。它将检查要调用的下一个函数。

当调用一个函数后,您希望另一个函数为同一路由运行时,会使用next()函数。

试试这个:

app.use('/add-product', (req, res, next) => {
console.log("This is add-product page")
return res.send("<form action='/product' method ='POST'><input type='text' name ='title'><button type ='submit'>Submit</button></form>");
});
app.use('/add-product',(req,res,next)=>{
console.log("This is add-product page")
res.send("<form action='/product' method ='POST'><input type='text' name ='title'><button type ='submit'>Submit</button></form> ")
next()
})

在你res.send(...)之后,你不能再在这里了。当您想要创建一个有条件的中间件时,请使用next()函数。

在向客户端发送响应时,应始终使用return。

const express = require('express')
const app = express()
app.use('/add-product',(req,res,next)=>{
console.log("This is add-product page")
return res.send("<form action='/product' method ='POST'><input type='text' name ='title'><button type ='submit'>Submit</button></form> ")

})
app.use('/product',(req,res,next)=>{
console.log('this is product-page')
return res.redirect('/')
})
app.use('/', (req,res,next)=>{
return res.send('Welcome to NodeJS')
})
app.listen(3000)

最新更新