Anoop K George
Anoop K George

Reputation: 1755

Django+React integration

I have Django Rest Framework server running in a terminal and React running in another terminal.

I consume Django API's in React using axios as mentioned below

    axios.get('http://localhost:8000/songs/').then(res=>console.log(res)

It work well,in production mode I will hook main.js (created by npm run build, the build file of React) to Django template.

Will this method work in server ? Is it recommended ?

I used to integrate Django + React with this guid (https://www.valentinog.com/blog/drf/) but it do not support some npm packages

Upvotes: 1

Views: 334

Answers (3)

Anoop K George
Anoop K George

Reputation: 1755

found useful document

https://cuckootechnologies.medium.com/integrating-django-rest-framework-with-react-js-9bf9d7f051a1

Django will run in one terminal and React will run in another terminal. The API from the Django server will be consumed by React using Axios.

Upvotes: 0

araldhafeeri
araldhafeeri

Reputation: 187

create constant.js file in your src react folder that contains all the api endpoints URLs. Like this:

const localhost = 'http://127.0.0.1:8000';

const apiURL = '/api';

export const endpoint = `${localhost}${apiURL}`;

export const productListURL = `${endpoint}/products/`;
export const productDetailURL = id => `${endpoint}/products/${id}/`;
export const addToCartURL = `${endpoint}/add-to-cart/`;
export const orderSummaryURL = `${endpoint}/order-summary/`;

Otherwise, you will have to change the endpoint domain on each request on the front end which can be time consuming.

I deploy apps on actual web-server like; ubuntu droplet on digital ocean, using NGINX. You can have both react, and Django app deployed on the same droplet. You just need to write extra configurations for nginx. And configure the webserver correctly.

react deployment docs: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-react-application-to-digitalocean-app-platform

django deployment docs: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04

Once you finish those both tutorials, you will understand how to configure your nginx for MVC.

Upvotes: 1

pplonski
pplonski

Reputation: 5859

Yes, it will work. There are several ways to deploy React and Django together.

However, my preferable way to deploy it is to use docker-compose and deploy it with nginx reverse-proxy.

Can you tell more details why some npm packages are not supported in Valentino Gagliardi tutorial?

Upvotes: 1

Related Questions