Hello fellow developers, today I will talk about the second class of full-stack BootCamp. I split this post into two parts because I am planning to make a more professional-looking structure with multiple layers.
Of course, we need to initialize npm by typing npm init
and hitting enter first.
- I took all the data from jsonplaceholder.typicode.com
nodemon
Before we start, we will install nodemon because it automatically restarts the server when we make changes. So, we do not have to quit from the current server and start the server again manually. Yeah, it is a lifesaver :)npm install -D nodemon
.-D
stands for devDependency which means it is used in the development process of the project and NOT when launching the project. It simply makes our lives easier. After that, under the script tag, add"start": nodemon express-api
. You can put anything after nodemon by the way. Finally, typenpm start
on the terminal to run nodemon. I am making this code for this blog, so I named it like this
Express.js
Type npm install express
and hit enter. After that, you should see this
Import express and create an app with it
const express = require("express"); // Imported express
const app = express(); // Created an app using express
Here is how to get routes:
const express = require("express"); // Imported express
const users = require("./data/users.json"); // imported users from data
const posts = require("./data/posts.json"); // imported posts from data
const app = express(); // Created an app using express
// when app gets `/users` (localhost:3000/users) send users data
//`res.send(users)`
app.get("/users", (req, res) => {
res.send(users);
});
// when app gets `/posts` (localhost:3000/posts) send posts data
//`res.send(posts)`
app.get("/posts", (req, res) => {
res.send(posts);
});
// Listens for requests from the server at port 3000
app.listen(3000);
However, what if the request from the client is only one user or a post. Something like localhost:3000/users/2 -> this means get me only user id 2. Add this code
app.get("/users/:userId", (req, res) => {
let user = users.filter((user) => user.id == req.params.userId);
res.send(user);
});
Explanation of the code above. Get me the users route /users/
that has userId (does not have to be userId, could be anything) /:userID
. Filter through users users.filter()
and bring me the one that matches user.id
(we get id from our users data) and with the link that client entered. We catch what client enters with req.params.userId
. If you used /:userId
then you use req.params.userId
. If you used /:whatever
then you use req.params.whatever