Let's create a simple Node.js API server which serves jokes stored in a JSON file.
For now: our datastore will be a JSON file on the file system of the Server =
Nex step: We will see how to put these jokes into a MONGO Database.
A MONGO database is a collection of JSON documents. Each document is a collection of KEY:VALUE pairs.
Here's your directory structure:
To get started, first, initiate a new Node.js project by running npm init -y in your terminal.
Next, install the needed dependencies. We'll use express to create the server and cors to handle Cross-Origin Resource Sharing:
npm install express cors
Now, let's create a index.js file and a jokes.json file in your project root.
Your jokes.json file could look something like this:
[
{
"id": 1,
"joke": "Why don't scientists trust atoms? Because they make up everything!"
},
{
"id": 2,
"joke": "Why was the math book sad? Because it had too many problems."
},
{
"id": 3,
"joke": "Why can't you give Elsa a balloon? Because she will let it go."
}
]
In your index.js file:
const express = require('express');
const cors = require('cors');
const fs = require('fs');
// Create an express app
const app = express();
// Enable CORS
app.use(cors());
// Load jokes from JSON file
let jokes = JSON.parse(fs.readFileSync('jokes.json', 'utf8'));
// Create a route to get all jokes
app.get('/jokes', function (req, res) {
res.send(jokes);
});
// Create a route to get a joke by id
app.get('/jokes/:id', function (req, res) {
const joke = jokes.find(j => j.id === parseInt(req.params.id));
if (!joke) return res.status(404).send('The joke with the given ID was not found.');
res.send(joke);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
This creates an Express server which will serve all jokes from your jokes.json file when someone sends a GET request to http://localhost:3000/jokes.
And if a client sends a GET request to http://localhost:3000/jokes/:id, it will return the joke with the specific id.
You can start your server with node index.js.
Now your server is ready to serve jokes!