Progress pill
NodeJS

Networking in NodeJS

  • Fetch()
  • JSON
  • Http server
NodeJS is often used as a language for backend: you can turn your script into a server, and also use it to make requests to other servers.
In thi chapter we're gonna introduce some basic networking features that will allow you to do that.

fetch()

If you want your program to download data from a website or an API, you need to make an HTTP request.
In modern versions of NodeJS, you can use the built-in fetch() function.
Here’s an example of making a GET request to an API:
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1") const data = await response.text() console.log(data)
When you run this, you’ll see something like:
{ "userId": 1, "id": 1, "title": "...", "body": "..." }
Here is what happens:
  1. fetch() takes a URL and makes a request.
  2. It returns a Promise that resolves to a Response object.
  3. response.text() reads the response body as a string.
But the string you get back is actually JSON. What is that?

JSON

When working with web APIs, the data is often sent and received as JSON, which stands for JavaScript Object Notation.
JSON is just a text format that looks a lot like JavaScript objects. For example:
{ "name": "Alice", "age": 30, "likes": ["apples", "bananas"] }
The JSON object is a built-in utility in JavaScript that can be used to work with this data format.
You can convert a JavaScript object into a JSON string using JSON.stringify():
const user = { name: "Alice", age: 30 } const jsonString = JSON.stringify(user) console.log(jsonString)
This prints:
{"name":"Alice","age":30}
You can also convert JSON text back into a JavaScript object using JSON.parse():
const jsonText = '{"name":"Bob","age":25}' const obj = JSON.parse(jsonText) console.log(obj)
This prints:
{ name: 'Bob', age: 25 }
Be careful: JSON.parse() will throw an error if the string is not valid JSON.
JSON.parse("not json") // ❌ Error!
So make sure the string is properly formatted.

http server

NodeJS allows you to create a web server without installing anything else.
You can use the built-in http module to handle requests from clients and send responses back.
Here is a very basic example:
const http = require("http") const server = http.createServer((req, res) => { res.statusCode = 200 res.end("Hello from NodeJS server!") }) server.listen(3000, () => { console.log("Server running at http://localhost:3000/") })
When you run this script and open http://localhost:3000 in your browser, you will see:
Hello from NodeJS server!
This is what's happening in the code:
  1. You imported the http server from the Node standard library.
  2. http.createServer() creates a server. You passed to http.createServer() a callback (req, res) => {...} to get executed every time someone connects.
  3. You assigned a status code of 200 (which indicates a successful operation) to the response. You can read about http status codes here
  4. res.end() sends the response and ends the connection.
  5. server.listen(3000) starts the server on port 3000.
You can also check req.url and req.method in the request to handle different paths or request types.
Example with routing:
const server = http.createServer((req, res) => { if (req.url === "/") { // handle requests for the root of the website res.statusCode = 200 res.end("Home page") } else if (req.url === "/about") { // handle requests for the about page res.statusCode = 200 res.end("About page") } else { res.statusCode = 404 // we send a 404 status code to signal that the requested page is missing res.end("Not Found") } })
These are very basic examples. For building more advanced servers, most devs would probably download a ready-made backend library like express.