Complete the code to create a basic Express server that listens on port 3000.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello from service!'); }); app.listen([1], () => { console.log('Server is running'); });
The standard port for local Express servers is often 3000. This code starts the server on port 3000.
Complete the code to send a GET request from one microservice to another using the 'fetch' API.
const fetch = require('node-fetch'); async function getData() { const response = await fetch('[1]'); const data = await response.json(); return data; }
The fetch URL must start with http:// or https:// for HTTP requests. 'http://localhost:3000/api/data' is correct.
Fix the error in the Express route to correctly parse JSON request bodies.
const express = require('express'); const app = express(); app.use([1]); app.post('/data', (req, res) => { res.json({ received: req.body }); });
To parse JSON bodies in Express, you must use express.json() middleware.
Fill both blanks to create an Express route that calls another microservice and returns its data.
const fetch = require('node-fetch'); const express = require('express'); const app = express(); app.get('/proxy', async (req, res) => { const response = await fetch([1]); const data = await response.[2](); res.json(data); });
The fetch URL should point to the other service's endpoint. The response should be parsed as JSON using response.json().
Fill all three blanks to implement a retry mechanism when calling another microservice.
const fetch = require('node-fetch'); async function fetchWithRetry(url, retries = [1]) { for (let i = 0; i < retries; i++) { try { const response = await fetch(url); if (response.ok) { return await response.[2](); } } catch (error) { if (i === retries - 1) throw error; } } } const maxRetries = [3];
Retries are set to 3 by default. The response is parsed as JSON. The maxRetries constant is set to 5 for flexibility.