JavaScript Programming/Node.js REST API/REST API
Appearance
index.html
[edit | edit source]<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-Control" content="no-cache">
<title>REST Server</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
th {
text-align: left;
}
td {
padding-right: 2em;
}
</style>
</head>
<body>
<h1>REST Server</h1>
<table>
<tr>
<th>Method</th>
<th>URL</th>
<th>Body</th>
<th>Returns</th>
</tr>
<tr>
<td>GET</td>
<td>/records</td>
<td></td>
<td>[{record}, {record}, ...]</td>
</tr>
<tr>
<td>GET</td>
<td>/records/1</td>
<td></td>
<td>{record}</td>
</tr>
<tr>
<td>POST</td>
<td>/records</td>
<td>{record}</td>
<td>{record}</td>
</tr>
<tr>
<td>PUT</td>
<td>/records/1</td>
<td>{record}</td>
<td>{record}</td>
</tr>
<tr>
<td>DELETE</td>
<td>/records/1</td>
<td></td>
<td>{record}</td>
</tr>
</table>
</body>
</html>
server.js
[edit | edit source]// This program uses Node.js and Express.js to create a simple REST API.
//
// References:
// https://medium.com/@onejohi/building-a-simple-rest-api-with-nodejs-and-express-da6273ed7ca9
"use strict";
const express = require("express");
const server = express();
const cors = require('cors')
server.use(cors());
const bodyParser = require('body-parser');
server.use(bodyParser.json());
let records = [];
let lastID = 0;
server.get("/", (request, response, next) => {
const path = require('path');
let filename = path.join(__dirname, "index.html");
response.sendFile(filename);
});
server.get("/records", (request, response, next) => {
response.send(JSON.stringify(records, null, 2));
});
server.get("/records/:id", (request, response, next) => {
let index = records.findIndex(record => record.id == request.params.id);
if (index == -1) {
response.status(404);
response.send("Not found");
}
else {
response.send(JSON.stringify(records[index], null, 2));
}
});
server.post("/records", (request, response, next) => {
let record = request.body;
record["id"] = ++lastID;
records.push(record);
response.status(201);
response.send(JSON.stringify(record, null, 2));
});
server.put("/records/:id", (request, response, next) => {
let index = records.findIndex(record => record.id == request.params.id);
if (index == -1) {
response.status(404);
response.send("Not found");
} else {
let record = request.body;
record["id"] = request.params.id;
records[index] = record;
response.send(JSON.stringify(record, null, 2));
}
});
server.delete("/records/:id", (request, response, next) => {
let index = records.findIndex(record => record.id == request.params.id);
if (index == -1) {
response.status(404);
response.send("Not found");
} else {
let record = records.splice(index, 1);
response.send(JSON.stringify(record, null, 2));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});