Show how to create and call an API endpoint
This template demonstrates how to:
GET
and POST
routeshttpCommand
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);
}
}
npm install -S express@^4.19.2 express-basic-auth@^1.2.1 body-parser@^1.20.2
//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');
});
httpCommand('GET', 'http://localhost:4000/')
const data = new URLSearchParams();
data.append('email', 'name@domain.com');
httpCommand('POST', 'http://localhost:4000/subscribe', data);
const data = { name: "Anthony" };
httpCommand(
'POST',
'http://localhost:4000/activate',
JSON.stringify(data),
{ 'Content-Type': 'application/json' }
);
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