More on Node, POST and Full Stack Websites
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
May 13, 2025
app.js
file in your project directorynpm init
to initialize a package.json
configuration file (you can keep pressing Enter to use defaults)npm install <package-name>
app.js
)app.js
npm install express
to install the Express.js packageconst express = require('express');
const app = express();
const PORT = 8080;
app.get('/posts', function (req, res) {
console.log("Endpoint /posts received a GET request.");
res.type("text").send("Hello World");
});
app.listen(8080, () => {
console.log(`Our first node app listening on port ${PORT}`);
});
req.body
.FormData
object to send POST parameters, which is always sent as multipart/form-data.req.body
params for multipart content.Client side
app.js
file configured properly AND that you are accessing your HTML document through localhost// GET endpoint
app.get('/path/:key', (rq, rs) => {
let ex1 = rq.params.key
let ex2 = rq.query.key
}
Simple book registry (title & author)
RESTful API endpoints (GET / POST)
Data stored in-memory
Static HTML pages consuming API via fetch()
fetch()
from different originsapp.use(cors())
;GET /api/books
→ res.json(books)
POST /api/books
→ validate body → books.push(...)
→ res.status(201).json(...)
app.listen(PORT)
// endpoint for getting a list of books
app.get('/api/books', (req, res) => {
res.json(books); originally
});
// endpoint for adding a book
app.post('/api/books', (req, res) => {
const { title, author } = req.body;
if (!title || !author) {
console.log("Error 400. Title and author required");
return res.status(400).json({ error: 'Title and author required' });
}
const newBook = { id: books.length + 1, title, author };
books.push(newBook); == this goes first
console.log("Code 201. Book created successful");
res.status(201).json(newBook); // HTTP 201 Created successful response status code
});
//add.html
document.getElementById('addBook').onsubmit = e => {
e.preventDefault();
const form = e.target;
const payload = {
title: form.title.value,
author: form.author.value
};
fetch('/api/books', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
}).then(() => location.href = 'index.html');
};
public/
folder in the root of the projectapp.use(express.static('public'));
<script>
uses fetch(‘/api/books’) to list books<form>
+ JS fetch() POSTs to /api/bookspublic/styles.css
fs
core modulefs.readFile(fileName, encodingType)
fs.writeFile(fileName, contents)
const fs = require('fs');
Write file
fs.writeFile('hola.txt', 'Hola mundo', (err) => {
if (err) {
console.log(`Error: ${err}`);
} else {
console.log('File successfully written!');
}
});
Read file
fs.promises
Using .then
/.catch
let contents = fs.promises.readFile('hola.txt', 'utf8');
contents
.then(console.log)
.then(() => { console.log('Done reading file!'); })
.catch(err => console.log(`Error: ${err}`));
Using async
/await
JSON.parse
JSON.parse(jsonString)
to turn a JSON string into an objectJSON.stringify(jsonObj)
to turn a JSON object into a string// Read JSON file and return parsed object
async function readJSON(filePath) {
const data = await fs.promises.readFile(filePath, 'utf8');
return JSON.parse(data);
}
// Write object to JSON file
async function writeJSON(filePath, jsonObject) {
const data = JSON.stringify(jsonObject);
await fs.promises.writeFile(filePath, data);
}
Web Programming