🎯 Master Your Career

Interview-Bytes

Expertly curated technical interview questions,
simplified into manageable lessons.

Showing 21–22 of 22 questions

21

☠️ Handling errors in Express.js ?

- Define error-handling middleware with 4 args: (err, req, res, next)

- Use next(err) to pass errors to the handler.

- For async errors, use try/catch and pass errors to next().

Code Instance
app.get('/', (req, res, next) => {
  try {
    throw new Error('Something went wrong!');
  } catch (err) {
    next(err); // Pass error to error-handling middleware
  }
});

app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).send('Internal Server Error');
});
22

📁How to serve static files in Express.js ?

- Use express.static('folder') to serve HTML, CSS, images, etc.

- For multiple directories, use express.static() multiple times.

- Can also add a virtual path prefix for custom routes.

Code Instance
// Serves from the 'public' folder
app.use(express.static('public'));

// Can serve static files from multiple folders
app.use(express.static('public'));
app.use(express.static('assets'));

// Access via website.com/static/file.css, instead of website.com/file.css
app.use('/static', express.static('public'));