Junior — Middle
Can you explain what is meant by 'interceptor' in programming?
sobes.tech AI
Answer from AI
In programming, the term "interceptor" refers to a component or function that intercepts and processes requests or data at a certain stage of their handling. It is often used to inject additional logic, such as logging, authentication, data modification, or error handling, without changing the main code.
In Node.js, for example, in frameworks like Express or NestJS, interceptors can intercept HTTP requests or responses, allowing for modification or additional actions.
An example of a simple interceptor in Express.js:
app.use((req, res, next) => {
console.log(`Request to ${req.url} at ${new Date().toISOString()}`);
next(); // pass control to the next handler
});
Here, the function intercepts all incoming requests and logs them without changing the main processing logic.