Category Archives: Node JS

DNY client (11 – Profile Photo Display)

Server side

First we put in the route

routes/user.js

Then we implement the function responder for when the user goes to /user/photo/:userId

Since we already retrieved the user object at function userById, everything is already in req.profile
We simply check for the image data, and then set the content type.

controllers/user.js

Client Side

we create a photoUrl so that our image control has a src.

src/user/EditProfile.js

However, there is an issue. The browser cache images and when you try to upload another image, and you come back to this page, the browser will be showing the old image.

In this situation, simply give the latest time and append it to the URL

DNY client (9 – Edit Users)

We first create our EditProfile component

src/user/EditProfile.js

Then, we add a Route to our EditProfile component. Whenever this link is clicked, it hits our EditProfile component.
src/MainRouter.js

Make sure we implement UpdateUser fetch operation, which does a PUT operation on the server for a particular user. That way, we can tell the server to update this particular user with this particular data.

Remember that when we give the user data in body, we need to stringify it. The server does not take objects as data. It takes a string.
If you were to send a body, the updateUser function on the server side won’t be triggered and it will be hard to debug. So make sure you always JSON stringify body data.

src/user/apiUser.js

EditProfile component source

Editing forms is about presenting a html form with textfield controls. We then put our state’s value in the textfield’s value property. Our state has already been updated with the latest value from the server via the initUserID function when the component was loaded.

DNY client (8 – Delete Users)

Client Side

removeUser tells the server side to look for the user with the specific ID. Then, remove that user from the database.

user/apiUser.js

auth/index.js

SignOutUser first looks at the client’s local storage. It removes the jwt key/value.
Then it tells the server to clear the cookie for this client.

Cookies are stored per-user on the users machine. A cookie is usually just a bit of information. Cookies are usually used for simple user settings colours preferences ect.

Cookies can be cleared through the browser’s settings via a “clear cookie” button. A cookie file can also be opened by the user when they go through your temporary Internet files history and can locate your cookie there. They can then open it and look at the contents. Hence, No sensitive information should ever be stored in a cookie.

We use server calls for removing the user and clearing the cookie in our DeleteUser functionality. After deleting is complete, we simply redirect the user to the home screen.

user/DeleteUser.js

Server side

controllers/user.js

DNY client (7 – Users)

Create the User file under user folder.

Include it into the router.

Then put it into the menu.

user/Users.js

The result is a list of users.

Props Change on Users

1) Go the users list http://localhost:3000/users
2) Click on View Profile link of any user. You’ll get to the profile page of that user with that user’s data.
3) If you were to click on your own profile link above, the component data wouldn’t change. This is because the URL is part of prop. Since you’ve changed the URL, you’re changing the prop. This change happens at this.props.match.params.userId.

This is the props of the component and when it changes, we need to fetch data for the profile user again. However, in our Profile component, we only do this for when componentDidMount. Thus, we need to implement fetch data in a component hook called componentDidUpdate like so:

user/Profile.js

DNY client (6 – Profile Page)

src/user/Profile.js

Notice when we added our Profile page, the path is /user/:userId.
This says whenever we have a URL in that format, we’ll hit the Profile component.

src/MainRouter.js

Use the user object you get from localStorage. Inside that object, you’ll get the user object. Access the _id of the user and use it for the url parameter when we click on the profile link.

src/core/Menu.js

When fetching data from Server

DNY client (5 – Menu and filtering authenticated content)

dny-client-5 source code
src/core/Menu.js

We first look at how we decide whether a link is active or not. We do so by looking at the history’s path name and the current path. If they match, then we’re on that page and we color it orange.

The way how we get history is to import withRouter from ‘react-router-dom’ and then using it as middleware on our Menu component.

The history object is returned to our component as an object. Within this object, we look at property location, and find the pathname of what page we’re on.

Then we implement signout functionality for when we click on sign out link.
1) We first clear out jwt from the local storage
2) we then make a request to the server for it to signout the current user.

Finally, we implment the filtering of which menu item should be visible depending on whether we’re authenticated or not.

Basically, if our local storage has jwt property, then we’re signed in. We need to get this string, parse it into an JS object, and return it. Else, if this jwt property is empty, then we’re not signed in.

We then copy and paste template html into our code. Then use the previous functionality for
1) signing out
2) filtering menu items
3) coloring the active link

DNY client (4 – Signing in)

We first create a sign in page routing in our MainRouter. It routes to component Signin

src/MainRouter.js

We then create component Signin. It has email and password for the user to sign in with. The error is required for erroneous situations and the redirect to a specific referer page.

src/user/Signin.js

We have an authenticate function that gets the jwt token and stores it into local storage. We store the token value on key ‘jwt’.

But before we do so, we need to make sure the window object exists.
Once the token is set, we set the referer to yes.

Once the user clicks submit, we sign by passing in the email and password. We stringify that data and put it in the body of our POST request to http://localhost:8080/signin.

When successful, we should then get the response with token and some data. We then put this token into the localstorage and set the our redirect to yes so that we redirect to the homepage.

Before you sign in, clear your localStorage first by opening up Inspect Element, then click on the Application tab. On the left-hand side, you’ll see a clearStorage. Click on it to clear any key/values stores previously.

Now, on the left-hand side, make sure you’re still on the Application tab click on the localhost URL. On your browser navigate to localhost:3000/signin. Then sign in using correct credentials. You’ll see that the key/value will be updated with the token given by the server. This is so that whenever you make future requests, you’ll be using this token with each request. The server will verify it and thus authenticate your requests.

After the successful sign in, you’ll be redirected to the home page.

DNY client (3 – Creating a User)

On the client side, make sure we create the event handler for the submit button:

src/user/Signup.js

On the server side, make sure use cors.

To set up: npm i -S cors

app.js:

Now when you fill in the username, password, email, (like I did in the screenshot) you’ll see that the password is ‘compaq’ and does not have a number. Thus, you’ll get a bad request:

Click on the Network tab to see what this bad request is about. You’ll see the request, which is called signup. Click on signup.

In the response from the server, we see that the text tells us that we need a number in our password:

So change our password so that it has a number. This time, when you submit, you’ll see that the response to our request will be successful. When you analyze the response to our request, you’ll see that the json response will have a success message:

Go into your mLab account and you’ll see that our users have the information we just used to create a user:

Now, if you try to submit the same data for registration, the response from the server will tell you that the email you’re using to register already exists:

DNY Node API (4 – sign in using JWT )

npm i jsonwebtoken

npm i cookie-parser

dnyNodeAPI-authentication

Creating a User

After creating a user correctly, we get a message saying that a user has been created.

Ensuring user creation correctness

In validator/index.js, we have function userSignupValidator function that ensures we check for the format of the data for when user is created.

We use this function as a middleware in
routes/auth.js

This means that userSignupValidator is used to validate the incoming JSON’s properties. Only when it passes do we continue on to signup function.

validator/index.js

Be sure that you include a number inside your password:

Make sure you include a name when you register for an account:

For your email, ensure to have it in an email format:

Successful Signin

In order to sign in, use /signin, then click on tab Body, choose raw and then JSON format.
Type in a JSON object with key/value “email” and “password”. Then click send. If your credentials are correct, you’ll get an object back with a token key/value.

Copy and paste the value into Headers. In Headers, create a key called “Authorization”.
In the value, type “Bearer ” with a space at the end. Then copy the token behind it.

You are not set up to create/update/delete posts, get/update/delete your own user data.

DNY node api (1 – setup)

  • download source
  • unzip the source code
  • go into directory and type npm install to install the modules
  • Once the packages are installed, run it npm run dev
  • Go to localhost:8080, then check terminal for logs

Set up

Open terminal, navigate to ‘Desktop’

mkdir dnyNodeAPI

cd dnyNodeAPI

npm init

press enter for all selections

npm install express

Then check your node_modules folder and you’ll see whole of packages being installed.

In our package.json file, change ‘main’: ‘index.js’ to ‘main’: ‘app.js’

Create file ‘app.js’:

in your terminal, if you went node app.js, it will run the server on port 8080.

But whenever we make a code change, we have to restart the server and this becomes cumbersome. So let’s install nodemon.

npm i nodemon

Then in your package.json:

Now, in your terminal, Ctrl+C to get out of whatever is running.
Then npm run dev.
It will run the command as specified in our package.json and we get the server running with constant updates.

Putting in Routes

routes/posts.js

app.js

Install Middleware

npm i morgan

Installing Database

Create account in mLab, and create a database. Select default for everything, i.e AWS, server at Europe, and create submit. Then ‘create db user’, and create a username and pwd for the db’s user.

Then, in your project, create a file .env:

.env

npm i dotenv

npm i mongoose

app.js

post.js

post.js