Znote (recipes)
  Get Znote  

API client-server

API client-server using ExpressJS and Fetch to start building or testing API

 

API client-server demo

Node backend with ExpressJS and client using fetch to start building or testing API

Package Installation

Install NPM packages

npm i -S express
npm i -S body-parser

Client

GET

const r = await fetch('http://localhost:4000/')
print(await r.text());

Post form with JS

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

const result = await fetch("http://localhost:4000/subscribe", {
        body: data,
        method: "post"
});
print(await result.text())

Post form with HTML

    <form action="http://localhost:4000/subscribe" method="POST">
        Email: <input type="text" name="email" id="email" required>
        <button type="submit">Submit</button>
    </form>

POST JSON

const data = {name: "Anthony"}
const result = await fetch("http://localhost:4000/activate", {
        body: JSON.stringify(data),
        method: "post",
        headers: {'Content-Type': 'application/json'}
});
print(await result.text())

Server

//exec: node
const express = require('express')
const bodyParser = require('body-parser');
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World')
})

// POST HTML Form
app.post('/subscribe', 
    express.urlencoded({extended: true}), 
    async (request, response) => {
  print(`email ${request.body.email}`)
  response.sendStatus(200);
})

// POST JSON data
app.post('/activate', bodyParser.json(), async (request, response) => {
  printJSON(request.body);
  response.sendStatus(200);
})

app.listen(4000)

Related recipes