0
0
Expressframework~10 mins

Microservice communication basics in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a basic Express server that listens on port 3000.

Express
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello from service!');
});

app.listen([1], () => {
  console.log('Server is running');
});
Drag options to blanks, or click blank then click option'
A5000
B8080
C3000
D80
Attempts:
3 left
💡 Hint
Common Mistakes
Using port 80 without admin rights
Using a port already in use
2fill in blank
medium

Complete the code to send a GET request from one microservice to another using the 'fetch' API.

Express
const fetch = require('node-fetch');

async function getData() {
  const response = await fetch('[1]');
  const data = await response.json();
  return data;
}
Drag options to blanks, or click blank then click option'
A'http://localhost:3000/api/data'
B'file://localhost:3000/api/data'
C'ftp://localhost:3000/api/data'
D'localhost:3000/api/data'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the protocol
Using wrong protocols like ftp or file
3fill in blank
hard

Fix the error in the Express route to correctly parse JSON request bodies.

Express
const express = require('express');
const app = express();

app.use([1]);

app.post('/data', (req, res) => {
  res.json({ received: req.body });
});
Drag options to blanks, or click blank then click option'
Aexpress.text()
Bexpress.urlencoded()
Cexpress.raw()
Dexpress.json()
Attempts:
3 left
💡 Hint
Common Mistakes
Using express.urlencoded() for JSON
Not using any body parser
4fill in blank
hard

Fill both blanks to create an Express route that calls another microservice and returns its data.

Express
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);
});
Drag options to blanks, or click blank then click option'
A'http://localhost:4000/data'
B'http://localhost:4000/info'
Cjson
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong URL
Using response.text() when expecting JSON
5fill in blank
hard

Fill all three blanks to implement a retry mechanism when calling another microservice.

Express
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];
Drag options to blanks, or click blank then click option'
A3
Bjson
C5
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Parsing response as text
Setting retries too low or too high without reason