Stream From an Express Endpoint

In the last lesson, you saw that a key in the page’s script reaches every visitor and that the fix is a route on the club’s own server. The starting project already has that server in server.js, but so far it only hands out the club’s page.

In this lesson, you’ll read the starter server, then add a route that takes a member’s message as JSON and streams the partner’s reply back as it’s written. You’ll test it from the terminal with curl before the page is involved.

Read the Starter Server

server.js uses Express, a popular npm package for writing web servers in Node.js. It was installed with the other packages when you ran npm install. Here’s the whole file:

Language: JavaScript Filename: server.js
import express from "express";

const PORT = 3000;
const app = express();

app.use(express.static("public"));

app.listen(PORT, () => {
  console.log(`Club page at http://localhost:${PORT}`);
});

The import line loads the package, and calling express() creates an app: the object that receives every request sent to the server and decides what to send back. The rest of the file configures that object.

The app.use(express.static("public")) line makes the app serve files from the public/ folder. A request for / gets public/index.html, the club’s page, and the page’s script loads the same way. That’s all you need to know about express.static() for now.

Last, app.listen() starts the server on port 3000, a number that distinguishes this server from other programs listening for requests on your machine. Once the server is listening, it runs the arrow function, which logs the address. Start the server from the project folder with node server.js:

Language: Program Output
Club page at http://localhost:3000

The command doesn’t return to the prompt, because the server keeps running and waits for requests. Open http://localhost:3000 in your browser to see the club’s page with its empty chat panel. Leave the server running, and open a second terminal in the project folder.

The page will send each member’s message to the server, which can’t answer it yet. To see what happens, send that request yourself with curl, a command-line program that sends an HTTP request and prints the response. It comes with macOS, Linux, and Windows 10 and later. Save Amara’s first message as a JSON body in amara.json, in the project folder:

Language: JSON Filename: amara.json
{ "message": "Hola, quiero una café con leche y un cruasán, por favor." }

Then send it to /api/partner, the path the partner’s route will have:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.