ย 
Znote (recipes)
ย ย Get Znote ย 

๐Ÿš€ Create a Node.js API with Express

Show how to create and call an API endpoint

ย 

๐Ÿš€ Create a Node.js API with Express

This template demonstrates how to:

  • Start a demo Express server
  • Handle GET and POST routes
  • Receive HTML form and JSON data
  • Protect endpoints with HTTP Basic Auth
  • Send requests with httpCommand

๐ŸŒ Global helper

This httpCommand function is usable in your current note

async function httpCommand(method, url, data, headers) {
  try {
    let options = { method, headers };
    if (method.toLowerCase() === "post") {
      options.body = data;
    }
    const r = await fetch(url, options);
    console.log(await r.text());
  } catch (err) {
    console.log(err);
  }
}

๐Ÿ“ฆ Install dependencies

npm install -S express@^4.19.2 express-basic-auth@^1.2.1 body-parser@^1.20.2

๐Ÿ–ฅ๏ธ Start the server

//exec: node

const express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');

const app = express();

// Simple GET route
app.get('/', (req, res) => {
  res.send('Hello World');
});

// POST route with HTML form data
app.post('/subscribe',
  express.urlencoded({ extended: true }),
  (req, res) => {
    print(`๐Ÿ“ง Received email: ${req.body.email}`);
    res.sendStatus(200);
  }
);

// POST route with JSON data
app.post('/activate', bodyParser.json(), (req, res) => {
  printJSON(req.body);
  res.sendStatus(200);
});

// Protected GET route using HTTP Basic Auth
app.get('/auth',
  basicAuth({ users: { 'tony': 'supersecret' } }),
  (req, res) => {
    print(`๐Ÿ” Authenticated user: ${req.auth.user}`);
    res.send('Welcome, authenticated user!');
  }
);

// Start the server
app.listen(4000, () => {
  print('๐Ÿš€ Server is running at http://localhost:4000');
});

๐Ÿ” Test the endpoints

1. GET request

httpCommand('GET', 'http://localhost:4000/')

2. POST form data (application/x-www-form-urlencoded)

const data = new URLSearchParams();
data.append('email', 'name@domain.com');

httpCommand('POST', 'http://localhost:4000/subscribe', data);

3. POST JSON data

const data = { name: "Anthony" };

httpCommand(
  'POST',
  'http://localhost:4000/activate',
  JSON.stringify(data),
  { 'Content-Type': 'application/json' }
);

4. Authenticated GET request (HTTP Basic Auth)

const username = "tony";
const password = "supersecret";
const auth = 'Basic ' + btoa(username + ":" + password);

httpCommand(
  'GET',
  'http://localhost:4000/auth',
  "",
  { 'Authorization': auth }
);

๐Ÿงช Tip: You can export the server code block as executable script file

Related recipes