Photo by Kevin Ku on Unsplash

Connecting Flask with Node.js.

A short tutorial on how to build a connection between Node.js and Flask.

Dhanam Parekh
Published in
2 min readNov 30, 2020

--

Introduction:

There are various reasons which require building a connection between Node.js and Flask. Recently, I did it in order to integrate my Machine Learning model implemented in Python with my website which uses Node.js as a backend. The procedure is quite simple. Let’s dive in without further ado.

Step 1: Build Flask Server

We first need to build the Flask server which will be listening to data sent from Node.js.

We are now running our server on port 5000 on our local machine. Additionally, we have created a simple route that will return a string back when a get request is sent from Node.js to the /flask endpoint.

Step 2: Build the Node.js Backend

In this step, we will lay out our backend using Node.js and Express.js. Express.js is a popular web framework used to build API’s.

We will use the request library which can be installed using npm. The request library is the most simple library designed to make http calls.

As we can see in the code, when a user visits the /home endpoint, a get request is sent to http://127.0.0.1:5000/flask which is our endpoint for the flask server. We will receive the string “Flask Server” as a response back from the Flask.

Result:

It’s time to check whether we are successful in getting a response from our Flask server. We can check using Postman which is a tool used to design and test API’s.

Screenshot by author

We can see that we receive the string “Flask Server”. Hence we are successful in creating the connection.

Conclusion:

As discussed above, there are various use-cases where connecting Node.js and Flask is useful. The most common use is when we need to add Machine Learning to our website since it is easier to implement Machine Learning in Python (due to super helpful libraries) and connect it to Node.js using Flask, rather than implementing it all together in Node.js.

--

--