API client-server using ExpressJS and Fetch to start building or testing API
Node backend with ExpressJS and client using fetch to start building or testing API
Install NPM packages
npm i -S express
npm i -S body-parser
const r = await fetch('http://localhost:4000/')
print(await r.text());
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())
<form action="http://localhost:4000/subscribe" method="POST">
Email: <input type="text" name="email" id="email" required>
<button type="submit">Submit</button>
</form>
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())
//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)