Performance: GET route handling
This affects server response time and how quickly the browser receives content to start rendering.
app.get('/data', async (req, res) => { // asynchronous processing or cached result const result = await getCachedResult(); res.send(`Result is ${result}`); });
app.get('/data', (req, res) => { // heavy synchronous processing let result = 0; for(let i = 0; i < 1e8; i++) { result += i; } res.send(`Result is ${result}`); });
| Pattern | Server Blocking | Response Delay | Security Risk | Verdict |
|---|---|---|---|---|
| Synchronous heavy processing in GET route | Blocks event loop | High delay (100+ ms) | Low | [X] Bad |
| Asynchronous or cached response in GET route | Non-blocking | Low delay (<10 ms) | Low | [OK] Good |
| Unparameterized DB query in GET route | Blocks event loop | Medium delay (50+ ms) | High | [X] Bad |
| Parameterized async DB query in GET route | Non-blocking | Low delay (<20 ms) | Low | [OK] Good |
app.get() method do in an Express app?app.get() method is used to define a route that listens for GET requests on a given URL path.app.post() handle POST requests, and app.listen() starts the server, so they do not define GET routes./hello that sends "Hello World" as a response?req first, then res. app.get('/hello', (res, req) => { res.send('Hello World'); }); reverses them, which is incorrect.res.send(). app.get('/hello', (req, res) => { res.write('Hello World'); }); uses res.write() which is not standard in Express, and app.get('/hello', (req, res) => { res.sendHello('Hello World'); }); uses a non-existent method res.sendHello()./user/42 with this route handler?app.get('/user/:id', (req, res) => {
res.send(`User ID is ${req.params.id}`);
});/user/:id captures the part after /user/ as req.params.id./user/42, req.params.id is "42", so the response is "User ID is 42".app.get('/data', (req, res) => {
res.send('Data received')
res.send('Another response');
});res.send() twice causes an error./product/:category/:id that responds with a message like "Category: electronics, ID: 123". Which code correctly implements this?(req, res) and use backticks with ${} to insert variables. app.get('/product/:category/:id', (req, res) => { res.send(`Category: ${req.params.category}, ID: ${req.params.id}`); }); does this correctly.req.params, not req.query. app.get('/product/:category/:id', (req, res) => { res.send(`Category: ${req.query.category}, ID: ${req.query.id}`); }); incorrectly uses req.query. app.get('/product/:category/:id', (req, res) => { res.send('Category: req.params.category, ID: req.params.id'); }); uses quotes, so variables won't be evaluated. app.get('/product/:category/:id', (res, req) => { res.send(`Category: ${req.params.category}, ID: ${req.params.id}`); }); swaps parameters.Pass the test and this pattern moves unknown