React Js With Node Js

Posted on  by admin

Uploading files might seem like a task that needs to be conquered especially in web development. In this tutorial, we will see how to upload a simple AJAX based file using Reactjs on front-end and Node.js on the back-end. This is easy to accomplish with the following technologies since the whole source code will be in one language i.e JavaScript.

To show you how to combine a Node.js backend with React Js front-end, we will be making the use of a simple file upload example. The topics we will be covering are:. Setting up a Back-end of the app using express-generator.

Using create-react-app to scaffold a front-end Reactjs app.

File Upload Form

Using axios for cross-origin API calls. Handling POST requests on our server.

Using express-fileupload, a promise based library. Lastly, connecting a Reactjs and Node.js. We will be starting without back-end first. We will write a server application with necessary configurations required to accept cross-origin requests and uploading files.

Overall Code

First, we need to install express-generator which is the official and quickest way to start with an Express back-end application. We will install this module globally from our terminal.

After installing this global npm module, we have an instance of it named express to generate our project structure. When changing the current directory to the project express command just scaffolded, we can observe the following structure and files:. To run this backend server on default configuration, we have to install the dependencies mentioned in package.json first.

Express-generator comes with the following dependencies. Some of them are essential to use such as morgan and body-parser and some we can ignore for this project.

I will be adding two more packages for our configurable back-end application to behave in the way we want to. cors provide a middleware function for Express applications to enable various Cross-Origin Resource Sharing options.

Creating the React.js Frontend

CORS is a mechanism that allows restricted resources (in our case, API or AJAX requests) on a web page from another domain.

  • It helps a browser and a server to communicate and can be hosted on separate domains.
  • You will understand it more when you will see it in action. The other module, express-fileupload is a bare minimum express middleware function for uploading files.
  • The advantage of it is that it supports for Promises and can handle multiple file uploads. With these two important packages added as dependencies in our project, we can now start by modifying the default Express back-end in app.js file.
  • In the above code, you would notice that we made some additions. The first addition we did is to import packages cors and express-fileupload in app.js after other dependencies are loaded.
  • Then just after other middleware functions, we will instantiate these two newly imported packages.

Running the Server

Also, we need to allow data coming from a form. For this, we have to enable urlencoded options of the body-parser module and specify a path in order to store the image file coming from the client. With this, we can see if our server is working correctly by running:. If you get the screen below by navigation on port http://localhost:3000, it means that our server is running perfectly.

Before we move to generate our front-end application, we need to change to port for our backend.

Conclusion

Since front-end application generated using create-react-app will also be running on port 3000. Open bin/www file and edit:. create-react-app is another command line utility used to create a default Reactjs front-end application.

We will also install the required library that we are going to use for making API calls to our backend server. index.js is the starting point of our application in the src/ directory.

It registers the render function using ReactDOM.render() by mounting App component. Components are the building blocks in any Reactjs application.

This App component comes from src/App.js. We will be editing this file in our front-end source code. We will be using the HTML form element that has an input. This provides access to the value, that is the file, using refs.

Ref which is a special attribute that can be attached to any component in React. It takes a callback function and this callback will be executed immediately after the component is mounted.

Setting up the Server

It can be also be used on an HTML element and the callback function associated will receive the DOM element as the argument.

  • This way, the ref can be used to store a reference for that DOM element. That is exactly what we are going to do.
  • The input element must have the type="file" otherwise it would not be able to recognize what type we are using it for.
  • It is similar to the values like email, password, etc. The handleUploadImage method will take care of the API calls that we need to request to the server.
  • If that call is successful, then the local state of our React application will be set to let the user know that the upload was successful.
  • Inside this function, to make the API call, we will be using the axios library that we installed when setting up our front end app.

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest.

Summary

It is primarily intended for use in sending form data but can be used independently from forms in order to transmit keyed data. To build a FormData object, instantiating it then appending fields to it by calling its append() method like we did above.

Since we are not using any styling, our form looks bare minimum.

But, you can go ahead and make it look more professional.

For brevity, I am going to keep things simple.

I recommend you to always enter a file name, otherwise, it will store the file with a undefined.jpg name.

Right now, we do not have in our server code to handle the POST request React app makes a request to.

We will add the route in our app.js in our Express application where the default route is defined.

This route gets triggered when a request is made to /upload/. The callback associated using the route contain req, res objects and access to next.

A standard way of defining a middleware function in an Express application.

The req object has the file and the filename that was uploaded during form submission from the client application.

If any error occurs, we return the 500 server error code.

Otherwise, we return the path to the actual file and console the response object to check if everything is working as expected.

  • .mv file is promise-based and provided to us by the express-fileupload package we installed earlier.
  • Try uploading an image file from the client now.
  • Make sure both the client and server are running from different terminal tabs at this point.
  • You should get a success message like this in your terminal:.
  • At the same time, the client is requesting to view the file on the front-end with a GET HTTP method.
  • That means the route /upload from the browser is successfully called and everything is working fine.
  • Once the file is uploaded to the server, it will be sent back to the client to reflect that the user has successfully uploaded the file.
  • You can find the complete code for this example at FileUpload-Example Github Repository.
  • Becoming a full-stack web developer can involve a steep learning curve since, at the very least, you'll have to learn how to code in three domains: 1) the persistence layer, 2) the application layer, which provides the logic, and 3) the view layer for rendering interfaces that the user can interact with.
  • In most cases, each of these layers will be implemented in a different programming language, thus increasing the amount of material you'll have to learn.
  • However, with Javascript, you can easily use a single programming language that encompasses all three layers making the learning experience a little bit more manageable.

In this guide, we'll take a look at how to build a simple backend server using Javascript Node.js as the application layer and React.js as the view layer that interacts with the backend to simulate the full stack experience.

  • The server application you'll be creating will be a mock API endpoint that returns JSON data.
  • Start off by creating a Javascript file called app.js with the following content:.
  • Using plain Javascript and Node.js, you can easily create a server application server that acts as an endpoint.
  • The line res.setHeader('Content-Type', 'application/json') forces the response to return data as JSON.

The function res.end() accepts a string version of a JSON object that contains a firstName and a lastName, which will be the payload of this endpoint.

  • The server application is started by running the line app.listen(port, hostname), whose parameters are set to the localhost and port number 3000 of the host machine.
  • Issue the following command in your terminal to start running the server:. Using your browser, visit the URL http://localhost:3000 and you should see the JSON object being returned with the following form:.
  • Once you've verified that your mock endpoint is working, perform the same action, but this time programmatically using a React.js frontend component.
  • Start off by creating a React component called PersonComponent with the following code:. This vanilla component will simply display the firstName and lastName state values.
  • Initially, these values are set as an empty string. Next, create a method that fetches data from your backend API, whose endpoint is http://localhost:3000. Create the following fetch method in your component:.

You first create a reference context whose value is this, referring to the instance of your component.

This will be used later on in the logic of the success function after the code has made a successful call to the API backend.

context will then invoke setState and update the React.js component's state values coming from response, which in turn is the JSON object that was returned by the API.

The last thing to do is invoke fetch automatically when the component is first mounted.

To do so, override the React.js component method componentDidMount() with the following logic:.

  • All that will do is call fetch once the component has been successfully mounted.
  • In turn, fetch will interact with the API, update the state, and force a re-render of the view with the updated values, thus completing the cycle.

In this guide, you've seen how to use a single programming language to implement both the backend and frontend components of your app.

  • This shortens the learning curve since you only have to focus on learning one programming language instead of a variety of languages that deal with different layers of your system.
  • In most cases, this can prove to be a much more agile approach to building applications since you can devote your time to going deeper with Javascript and understanding its more advanced intricacies while still being able to contribute to all parts of your tech stack.
  • Adding a persistence layer will be easier as well since you just have to look for an abstraction layer, also written in Javascript, that provides API calls for the underlying database.

Getting Started

For any questions or concerns, or if you simply want to chat about programming in general, hit me up @happyalampay!

Create a Node.js project. Add npm packages. Add React code to your app.

  • Attach the debugger. Starting in Visual Studio 2022, you can alternatively create a React project using the new CLI-based project type.
  • Some of the information in this article applies only to the Node.js project type (.njsproj).

What is Node.js? Node.js is a server-side JavaScript runtime environment that executes JavaScript code. The default package manager for Node.js is npm.

Setting up Front-end

A package manager makes it easier to publish and share Node.js source code libraries.

The npm package manager simplifies library installation, updating, and uninstallation.