Как связать бэкенд и фронтенд node js

Обновлено: 26.04.2024

In this article, I’ll walk you through the process of creating a simple React app and connecting it to a simple Node/Express API that we will also be creating.

I won't go into much detail about how to work with any of the technologies I will mention in this tutorial but I will leave links, in case you want to learn more.

You can find all the code in this repository I made for the tutorial.

The objective here is to give you a practical guide on how to set up and connect the front-end client and the back-end API.

Before we get our hands dirty, make sure you have Node.js running on your machine.

Create the Main Project directory

In your terminal, navigate to a directory where you would like to save your project. Now create a new directory for your project and navigate into it:

Create a React App

This process is really straightforward.

I will be using Facebook’s create-react-app to… you guessed it, easily create a react app named client:

Let’s see what I have done:

  1. Used npm’snpxto create a react app and named it client.
  2. cd(change directory) into the client directory.
  3. Started the app.

If all is ok, you will see the react welcome page. Congratulations! That means you now have a basic React application running on your local machine. Easy right?

To stop your react app, just press Ctrl + c in your terminal.

Create an Express App

Ok, this will be as straightforward as the previous example. Don’t forget to navigate to your project top folder.

I will be using the Express Application Generator to quickly create an application skeleton and name it api:

Let’s see what I have done:

  1. Used npm’s npx to install express-generator globally.
  2. Used express-generator to create an express app and named it api.
  3. cd into the API directory.
  4. Installed all dependencies.
  5. Started the app.

If all is ok, you will see the express welcome page. Congratulations! That means you now have a basic Express application running on your local machine. Easy right?

To stop your react app, just press Ctrl + c in your terminal.

Configuring a new route in the Express API

Ok, let’s get our hands dirty. Time to open your favorite code editor (I’m using VS Code) and navigate to your project folder.

If you named the react app as client and the express app as api, you will find two main folders: client and api.

  1. Inside the API directory, go to bin/www and change the port number on line 15 from 3000 to 9000. We will be running both apps at the same time later on, so doing this will avoid issues. The result should be something like this:


2. On api/routes, create a testAPI.js file and paste this code:

3. On the api/app.js file, insert a new route on line 24:

4. Ok, you are “telling” express to use this route but, you still have to require it. Let’s do that on line 9:

The only changes are in line 9 and line 25. It should end up something like this:


5. Congratulations! You have created a new route.

Connecting the React Client to the Express API

  1. On your code editor, let’s work in the client directory. Open app.js file located in my_awesome_project/client/app.js.
  2. Here I will use the Fetch API to retrieve data from the API. Just paste this code after the Class declaration and before the render method:

3. Inside the render method, you will find a tag. Let’s change it so that it renders the apiResponse:

At the end, this file should look something like this:


  1. On lines 6 to 9, we inserted a constructor, that initializes the default state.
  2. On lines 11 to 16, we inserted the methodcallAPI()that will fetch the data from the API and store the response onthis.state.apiResponse.
  3. On lines 18 to 20, we inserted a react lifecycle method calledcomponentDidMount(),that will execute thecallAPI()method after the component mounts.
  4. Last, on line 29, I used the tag to display a paragraph on our client page, with the text that we retrieved from the API.

What the heck!! CORS ?

This is simple to solve. We just have to add CORS to our API to allow cross-origin requests. Let’s do just that. You should check here to find out more about CORS.

  1. In your terminal navigate to the API directory and install the CORS package:

2. On your code editor go to the API directory and open the my_awesome_project/api/app.js file.

3. On line 6 require CORS:

4. Now on line 18 “tell” express to use CORS:

The API app.js file should end up something like this:


Great Work. It’s all done!!

Ok! We are all set!

Now start both your apps (client and API), in two different terminals, using the npm start command.


Of course, this project as it is won’t do much, but is the start of a Full Stack Application. You can find all the code in this repository that I’ve created for the tutorial.

Next, I will work on some complementary tutorials, like how to connect this to a MongoDB database and even, how to run it all inside Docker containers.

После всех манипуляций (npm install / правка конфиг файла) пытаюсь запустить приложение. Если запускать из корневой директории (npm run dev) запускается бэкенд на localhost:3000. Если запускать из поддиректории frontend (npm run serve) запускается фронтенд на localhost:8080. Полагаю, что это не совсем правильный способ запуска подобных приложений, поскольку в самом репозитории все запросы из фронтенда в бэкенд идут относительными путями (/api/v1/settings, например). Иными словами, как правильно нужно запускать подобные приложения на nodejs, чтобы фронт и бек работали на одном хосте?

1 ответ 1

Нужно в начале собрать фронтенд: cd frontend && npm install && npm run build

Затем нужно запустить бек: в корне проекта(не frontend , а всего проекта) нужно запустить сервер через node server.js

Сервер будет запущен на порту из конфига (3000, если не указан).

Теперь о том как это работает. После запуска npm run build фронт собирается в статику - frontend/dist . После запуска сервера он будет перенаправлять все запросы на фронт (кроме серверных вида /api/*** ), за это отвечает строка в server.js :

Только начал разрабатывать приложения, никак не соображу. Как связать frontend - на React и сервер на Node.js?
Удалённо - купил VPS, настроил, выложил node.js , запустил. С браузера открыл своё React приложение, отправил AJAX запрос, и я получил ответ с своего сервера. Окей. А как мне простите разрабатывать все локально? Я запустил приложение npm node app.js на 8000 порту. Запускаю своё реакт приложение через npm start, оно открывается на 3000 порту. Но Ajax запросы не получают никакого ответа. Пробовал выставлять заголовки "Content-Type": "application/json",
"Access-Control-Allow-Origin":"*" , на удаленном сервере это дало результат. Локально , не дало. Как разрабатывать локально ?

  • Вопрос задан более года назад
  • 164 просмотра

dyuriev

Как же сильно я (не) люблю эти вопросы про node.js и порты.

Ставите себе nginx на локалхост который роутит правильно запросы с 80 порта до 3000 или 8000 порта в зависимости от запроса и живете себе радуетесь.


The original purpose, and it remains the most common use case for Webpack, is front-end javascript bundling. This involves bundling a piece of javascript code, and all its dependencies into a single javascript file that can be served as a static javascript and referenced from a HTML page.

If you are unfamiliar with front-end javascript bundling, the next section serves as a crash course introduction else skip straight to the next section ‘Webpack Front-end and Back-end Javascript Bundling’.

This article is about using Webpack to not only bundle your front-end javascript, but the back-end javascript as well, in the case where you are using a javascript-based backend such as nodejs.

One good reason for using Webpack for your nodejs back-end is that you are already using Webpack for your front-end, and you want to streamline your build tools.

The motive for writing this article is two-fold:

  • Explain the differences in using Webpack for back-end vs. for front-end javascript bundling
  • Provide step-by-step instruction to bundle javascript for both back-end, and front-end

Webpack Front-end Javascript Bundling Crash Course

This introduction is based on the example on the official Webpack site.

  1. You write a function, etc., inside a module, packaged in a file (bar.js)

2. You import the module and use it with other libraries, e.g., React (front-end framework) in your front-end javascript code (front.js)

3. You use webpack to create a bundle, i.e., a single javascript (‘bundle-front.js’) containing all dependencies (bar module, React library, etc.) with ‘front.js’ as the starting point.

4. Run the javascript code in ‘bundle-front.js’ file on your web page

Front-end vs. Back-end Javascript Bundling

Front-end javascript bundling is used in any project regardless of their back-end stack, which can be ruby, python, etc. The front-end javascript bundle output is merely served from the back-end stack as a static javascript file.

The confusion starts when the back-end stack is also javascript-based, e.g., nodejs. Are you then trying to bundle the javascript for front-end, back-end or both when you use Webpack?

You have 2 choices:

  1. Use Webpack for bundling front-end javascript code as described, and Gulp or Grunt for building your back-end javascript code. The disadvantage is there is a lot of effort and setup redundancy in managing both build systems.
  2. Use Webpack for bundling both front-end and back-end javascript code. Most people are not aware that you need to bundle the front-end and back-end javascript code ‘separately’, creating 2 output bundles

A. Distinct Webpack configuration files for front-end and back-end

B. Unified Webpack configuration file for both front-end and back-end

A. Distinct Configuration Files For Front-end and Back-end

The simplest way is to create 2 Webpack configurations

  • webpack-back.config.js
  • webpack-front.config.js

You run Webpack command twice, each time using a different configuration file to generate 2 output bundles, e.g., bundle-front.js, and bundle-back.js.

You start your backend server with ‘bundle-back.js’ using:

And on your main html page you run ‘bundle-front.js’ as follows:

The differences in the Webpack configurations are the following parameters:

  • target
  • entry
  • output
  • externals
  • devServer
  • devtool
  • For back-end, this is ‘node’, for front-end, this is ‘web’
  • The entry points (source files) for the back-end and front-end javascript points to different source javascript files, i.e., ‘back.js’, and ‘front.js’ respectively
  • The generated javascript bundle file for back-end and front-end are different files, i.e., ‘bundle-back.js’, and ‘bundle-front.js’ respectively
  • The ‘webpack-back.config.js’ imports the nodeExternals method from ‘webpack-node-externals’ library
  • This method returns the list of dependency libraries in ‘./node_modules’ directory and putting the list into ‘externals’ exclude them from being bundled
  • For back-end, all the dependency libraries is installed into ‘./node_modules’ with yarn install or npm install during build time thus there is no need to include them in the back-end bundle
  • The front-end, on the other needs all dependencies to be bundled because the bundled javascript needs to be a stand-alone unit as it will be loaded and run on the user’s browser
  • Only for front-end bundling. This sets up the webpack-dev-server, which eliminates the need to setup a webserver to serve the front-end bundle as a static javascript file during development. Moreover, it can automatically re-bundles the front-end bundle if it detects changes in the source code, to increase productivity; you do not have to restart your server, and reload your browser.
  • Indicates the details in the sourcemap, which is used by the browser to tie the front-end javascript bundle execution to the original front-end javascript source code, which is useful for debugging
  • Only for front-end since back-end javascript has their own debugging tools

B. Unified Configuration Files For Front-end and Back-end

It is possible to combine webpack-back.config.js and webpack-front.config.js into a single webpack.config.js, which requires 3 steps:

  1. Combine all the ‘require’ statements and put them at the top
  2. Shove the ‘webpack-front.config.js’, and ‘webpack-back.config.js’ into two separate const s
  3. Combine the ‘module.exports’ and put them at the bottom to export the const s holding the webpack configurations

This enables us to generate the back-end, and front-end bundles with a single Webpack command.

However, I have encountered issues where the webpack-dev-server cannot start properly depending on the order of clientConfig, and serverConfig.

For details, see Webpack ‘targets’ concept page. react-starter-kit use a single webpack.config.js file as well. Neither examples however has ‘devServer’ configured.

Common Error Messages

The most telltale sign that you are not bundling front-end and back-end bundle correctly is when you see messages similar to :

You are trying to use a node-based module in the front-end bundling.

The easiest way to solve this is to specify the ‘target’ in the Webpack configuration for your front-end ‘webpack-front.config.js’, as pointed out above.

If the case that problem persists, add the following to the Webpack configuration


Many of us, including me, would have struggled to develop a React app connected to a Nodejs backend! Today, through this article, I will show you the basics of connecting these two, and Bonus !, how to publish the site to Vercel (including the backend and frontend)

I am not going for a chat or other applications, but a small ‘Hello World’ example !

So let’s dive into it…

Prerequisites:

  • Latest version of node installed
  • Have an account set up in Vercel
  • Latest version of vercel-cli installed and logged-in

That’s all you need !

First of all, install the package ‘create-react-app’ using npm i create-react-app -g in your command-line. (For this tutorial, I am using the Windows CMD).

After the installation, you can go to the folder, where you want to create your front-end ( using the cmd ). In your folder, type npx create-react-app firstapp ( You can change the firstapp according to your wish )


After the installation, type cd firstapp then code . This will open the VSCode. ( You can use your preferred code editor. I will be using VSCode for now ).

Now comes the cleaning process. In your project’s root. you can go to the src folder. Inside it, you may delete the App.test.js and setupTests.js as these are not needed!

The good news is that we have finished the client-side installation !

Now, let’s dive into your code. As I said above, I am only going to the ‘Hello-World’ example. For this, let’s navigate to the App.js in the src folder. You may remove all the code inside the After deleting, add this piece of code to the very top of your (whole) code: import React, < useEffect >from “react"; Now you should have something like:

Next, inside the the function App() add:

Now your whole App.js may look like this:


By using UseEffect Hook, you tell React that your component needs to do something after render. React will remember the function you passed ( and call it later after performing the DOM updates.

Next, let’s run the app by going to the Terminal > New Terminal in VSCode. In the terminal type npm start . This will open localhost:3000 for our development. Now you may see, in your browser’s console, ‘This only run once!’ printed !

You may close the development server by pressing Ctrl + c then hitting enter in the terminal!

Next step is to install axios . Even though, it is not needed now, we are going to complete it. Open a new terminal and type npm i axios . After the installation is complete, navigate to the src folder and create a new file called axios.js . Inside it, add this piece of code:

As, I already said, this is not important for now, but we need it anyway!

The good news is that we have finished the client-side set-up !

Navigate to the root of your project. Create a new folder called api . Now, in your terminal, navigate to the api folder by cd api . Then in the terminal, type npm init . This will create us a package.json . This may ask us a few questions. But the important one is the entry-point . For that question, just type server.js . For others, just hit the enter.


Now, in your backend folder ( api folder ) you may see a package.json . The content of it should be like this:


Now let’s make some changes !

Create a new terminal. Type cd api then npm i nodemon --save-dev . After this process, navigate to your package.json. Add this line, inside the "scripts"

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

Next is to add a .gitignore file in your backend ( api folder ). Inside the .gitignore file, add:

A gitignore file specifies intentionally untracked files that Git should ignore.

The good news is that we have finished the server-side installation !

Lets’ dive into our Server-side set up.

Firstly, let’s install express . In your terminal, navigate to the api folder. Type npm i express --save .

Then, you may create a server.js file in the backend ( api folder ). Inside the server.js add these:

process.env.PORT || 5000 means: whatever is in the environment variable PORT, or 5000 if there’s nothing there.

Now in the terminal ( in the api folder ) type npm start . You may see:


Now, you can close the server ( by pressing Ctrl + c then hitting enter key ).

In your server.js , before the server.listen add:

The express.json() parses incoming requests with JSON payloads and is based on body-parser.

The express.urlencoded() is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

When a Request is made to ‘/api/hello’ , the server will send, as the response, “Hello World” also set the response status as 200.

Now the server.js will look like:


That’s it! ( you may close the server for now! )

The good news is that we have finished the server-side set up !

Go to your frontend package.json . Inside it add:

Next, you want your backend and frontend running at the same time! For that you may need the package npm-run-all . Install it in the frontend of your project by npm i npm-run-all --save-dev . After the installation, you have to make some changes in your frontend package.json . Change all of the code in the "scripts" in the package.json to:


Now in the terminal, (in the root of your project) start your project by npm start

Now, in your src > App.js :

After this, your App.js will look like:

Now, in your code, you may see axios.get("api/hello") . Here, there is no need of ‘/’ before the “api” as I said in the Client Side Set-Up.

The good news is that we have finished connecting the front-end and back-end!

The last and final step is to show the result of the fetch in the UI. For that, rewrite the App.js to:

In the first line, we added the code to import useState from ‘react’. Then we created a new State called ‘result’. After when the fetch is completed, we set the ‘result’ as the response.data ( which is the “Hello World” from the server code ). Then a h1 tag to display the result in the UI

The good news is that we have finished showing the result in the UI !

Before we could publish the app to Vercel, we need to create configuration file for Vercel. We add that file in the root of your project and should be named vercel.json . Inside it add:

Now let’s dive into the production part ! ( You should meet the prerequisites mentioned above for this step )

Using the terminal, in the root of your project, type vercel --prod .

This will promote your site to production and will ask some questions and the answers you provide must be:


You can go to the link given as ‘production’. That’s it

The good news is that we have finished publishing your site !

That’s all for today ! If you got bored reading this article, find this interesting tip: How the name ‘Github’ was formed ? By joining the letters ‘G-i-t-h-u-b’. That’s it ! The good news is that we have finished reading my little joke !

If you haven’t read my next(from future) article, find it here.

Читайте также: