Search code examples
reactjsdjango-rest-frameworkdjango-react

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


Solution

  • 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.