How to Send Form’s Data with Fetch using GET, POST, PUT, DELETE and Catching with Express.js

Rodrigo Figueroa
Geek Culture

--

Hi again! Sorry for the delay, but this is great information, and it is too much data to analyze, but it is worthy, We are going to use GET, POST, PUT, DELETE with fetch method and the best part is that we will catch all the data with Express.js this is awesome! I will share the code.

-Video on YouTube
-Directory
-NPM
-Structure
-Express.js server
-GET Request Method
-POST Request Method
-POST Request Method using Fetch
-PUT Request Method using Fetch
-DELETE Request Method using Fetch
-Conclusion

If you want, you can watch it too!!

Create a Directory

Where you can add the package JSON and the node_modules, views, layouts and our JavaScript file.

Example Directory
Example Directory

I Created a directory call formjs you can call it whatever you want, but you need a directory that you only need to this project.

Initiate package JSON

You need to run this command to initiate the package JSON, and then we can start installing packages.

npm init -y

This command will create our package JSON

Create Package JSON
Create Package JSON

Install dependencies

We need to install express and express-handlebars to make our server dynamic.

Example install dependencies
Example install dependencies

Run this commands

npm i --save express express-handlebars

With these commands we actually add express and express handlebars, we will work with them remember that express-handlebars after the 6.0.2 you need to call the engine instead of saving on a variable.

Structure

The structure is simple just create a directory call views and inside we need to create layouts and add all the views and layouts that we require for the project, in this case home, form, 404, 500, main, thank-you and that is all for now.

Example structure handlebars
Example structure handlebars

Then we need to add information to every view and main

To the main page (Layout)

Example adding information to the main layout page
Example adding information to the main layout page
Example adding information to the Home view
Example adding information to the Home view
Example adding information to the thank-you view
Example adding information to the thank-you view
Example adding information to the 404 view
Example adding information to the 404 view
Example adding information to the 500 view
Example adding information to the 500 view
Example adding information to the Form view
Example adding information to the Form view

Remember that on the form view we will add more information and form and scripts to send the data for now adding the h1 is okay.

Create Express.js server

Then we need to create our Express.js server we start adding variables and saving express, express-handlebars, port and after that we need to add the engine and set the view of the server after that we need to handle the request clients for pages in this case home, form, and thank you for now and render its respective view.

Example to create simple server with Express.js
Example to create simple server with Express.js

As you see we add the engine to handlebars and the default layout (main) then we specify the engine in this case handlebars, then we take the requests and change to the render view that the user needs, and finally, we listen for request with app.listen and the server is on http://127.0.0.1:1024 in this case.

Example 404 and 500 views
Example 404 and 500 views

We do not forget the 404 and 500 server error views.

GET Request Method

In this case, we are going to get all the users from the server.

Let’s open our server.js file and create a variable called USERS, and it will be an Array of objects (users)

Example variable Users inside our server.js file
Example variable Users inside our server.js file

After that we need to create the response to the client, adding URL and the function with the request and response parameters and it will response the USERS but in JSON format.

Example complete for GET, response USERS
Example complete for GET, response USERS

Then we should go to the form view and add ul with the id “users”, li and button with the id “getUsr” HTML tags, with this we can start

Example adding tags to our form view
Example adding tags to our form view

Then we create a script file where we will add all the JavaScript and fetch method to send and get data, in this case get data.

Save the ul and the button into a variable, call ul and btn if you want

Example variable ul and btn saving tags
Example variable ul and btn saving tags

And to add the users into our ul we need to use fetch but we need to add and eventListener to the button, using the preventDefault to refresh the page, and call the fetch method with the URL of the get server where we can get the users because fetch use promises we use the then method to return the JSON format of the data that the server gave us and finally we use the innerHTML to add all the users from the server and the join method to join all the string.

Example btn click event and geting all the users from the server and print in on the ul
Example btn click event and geting all the users from the server and print in on the ul

Result of the GET users from the server and we can see that we add all the users from the server to our ul and li tags

Example result get all the users from the server with GET
Example result get all the users from the server with GET

POST Request Method

To make a POST request first of all, we need to create the method in our server.js file.

Example POST method with function and request and response parameters
Example POST method with function and request and response parameters

For now because in this example we are going to use the formData POST like my last POST, but we will change some things, well we need to specify the URL, and we can push to the USERS Array, but this is for the next example in this instance we are going to send it to the thank-you page.

Let’s create the form to our form view

Example POST data with FormData
Example POST data with FormData

We create the form adding the attributes like method post, action to the POST URL and id, in this case the same as we wrote on the server.js file then we need to add to each input the name because it is really important with this the server knows the exact information and values.

Example common form data page view
Example common form data page view

But if we click on the Send Common Data button, we will have nothing :(

Example output console log after the POST
Example output console log after the POST

Why! This is really important, guys! Because Node.js use middlewares, and we actually need to add a middleware to our server.js file

Example adding Middlewares to our server.js file
Example adding Middlewares to our server.js file

After our server variables we need to add this middlewares the first is for simple text data request (x-www-form-urlencoded) and the second one is to send JSON data (application/json) in this case Express.js knows what kind of data is sending the client, and we can catch it!

Add them and re-run our server.js, click on the button and cool!

Example output server.js and data from Form
Example output server.js and data from Form

POST Request Method using Fetch

Then we will do it with Fetch method first we need to create our POST method in our server.js file, in this case we will save the user

Example POST method in our server.js file with push to the USERS Array
Example POST method in our server.js file with push to the USERS Array

This is when we will push the new user to our USERS Array first, we need to start with a try and catch statement with this we can save our server to fail second we start with a tiny validation with the find method to search for the userName (we can add more validations but for now this is great) add an if statement if exist it will send to the user that the user exist, and if not it will loop searching for the right id, and we need the use of Object.assign to join the { id: n } to the req.body object and with this pushin to the USERS array and on the response return a JSON with the success: true, if there is any problem it will catch it and sending error to the user, and we can manage that error later.

Let’s go to the form view and clone our last form, but changing the id and removing the method and action.

Example creating form to the form view
Example creating form to the form view

Let’s create our script, we need to add a variable call fm2 and save the form tag

Example saving the form_2 to the fm2 variable
Example saving the form_2 to the fm2 variable

To start we need to add an eventListener to the fm2 but instead of click we use the submit then add the preventDefault method to stop the refresh of the page and create a constant variable call o, and empty object where we can add all the name and values from our form with the FormData’s Object, second we need to initiate the fetch method and add the URL from the POST server and we have to specify the method, headers and add the body in this case is POST, ‘Content-Type’: ‘application/json’ and the stringify o object, add one then to receive the raw data then transform it to JSON and send the data to the console.

Example send POST data with fetch and with the submit of the Form
Example send POST data with fetch and with the submit of the Form

We can see that it is sending the data to our server and don’t forget to add the JSON middleware!

Example server’s output from client
Example server’s output from client

Let’s click the Get Users button again, and we will have our new user from the server that is really great!

Example form view POST user and get all users again
Example form view POST user and get all users again

PUT Request Method using Fetch

With the PUT request we can update the user from our USERS Array, first we need to add the put method to our application (server), server.js file, but to search for the right user we need to use the req.params.id in this case we will use the find method again to search for the user and if the users is found we can update the name, age, or goal it depends on the information of the client that is why we add the if statement to check if exits and if not the response is status 404 user not found, this is important to add the :id because we need to specify the id of the user who will be updated.

Example put method in our server,js file updating the user
Example put method in our server,js file updating the user

Let’s create our form to update our user

Example create update form from form view
Example create update form from form view

Then let’s create the script, it is almost the same as the POST script we only need to change the method to PUT, and the URL because in this case we need to specify the user’s id and adding to the URL to match the user that we need to update.

Example script to update the user with fetch
Example script to update the user with fetch

Let’s update Jake’s user to Flame Princess, and we need to click again to the get Users and see what is happening, and we can see that we see the change correctly.

Example update the user with fetch form view
Example update the user with fetch form view
Example update succesfully
Example update succesfully

DELETE Request Method using Fetch

Finally, we have the DELETE request method, and we need to create it on our server.js file for this method we only need to use the findIndex method to make a comparison with the req.params.id to match the user who is going to be deleted then if it is existed we just make an if statement to delete it with splice and if not we return the response telling that we can’t find the user 404 not found.

Example create request DELETE method in our server.js file
Example create request DELETE method in our server.js file

Second, let’s create a button to delete each user with just one click, for this we have to change a little the GET request method in our form view script, but first we need to add a button after the information of our user and with the data-delete equal to the id of the user because with this we can call an addEventListener to fetch and delete the user for the fetch method we need just to change the method to DELETE, then we need to use the e.target.dataset.delete for the users’ id also adding to the URL, and with this it will delete the specific user.

Example adding button to the GET user and adding fetch method to delete it
Example adding button to the GET user and adding fetch method to delete it

Check the DELETE request method

Example adding more users
Example adding more users
Example Deleting all users with the DELETE request method
Example Deleting all users with the DELETE request method

It looks great!

Conclusion

In conclusion, these examples are really great! Because they show the common ways to create, update, delete and to get users from the server, using fetch because it is really useful and we need to specify some configurations but we can catch errors and use promises to be neater, for me is amazing because I am learning a lot of new thing with Node.js and Express.js with this we can enhance validations or we can mix with Mongodb but for now it’s really amazing how we can use this small example to create something amazing!

Thank you for Reading and for your support, I am really glad to have you all!!!

If you want to send me recommendations or just say thank you or Hi you can send me a DM to my Twitter account or you can just write a comment.

Sources

Video

--

--

Rodrigo Figueroa
Geek Culture

I’m a Web Developer, fanatic of books and Smash Player.