Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - Express.js: send results after next() is called

I have an app that enables users to define their own routes on the fly. And I still want to display an custom 404 message, so in the last middleware I do this:

app.use((req, res, next) => {
  // ...normal logic

  // check for user defined routes 
  next()
  // if res is not written, i.e. request not processed by user defined routes
  if (!res.writableEnded) {
    res.status(404).send(`not found!`)
  }
})

However, I got

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

. How can I implement this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no way for middleware to know if a subsequent route handler is going to pick up the path.

You need to define it last, really last, after any user defined routes.

Then you need to not call next().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...