Django+React integration - reactjs

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

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.

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?

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.

Related

React App doesn't make proxy calls after deployed to azure

Simple setup:
React App created with create-react-app
ASP.NET Core web API - a couple of controllers (currently no security until I make it work)
Both the API and Application are deployed to Azure.
When I run the app locally with configured proxy (I contact the deployed API on Azure) it works correctly makes the calls.
If I try the API directly from my machine it works too (PostMan for example)
When I open the deployed React APP - The application loads correctly but the call to the API doesn't get proxy(ed). What I mean it's not returning 404, 403 - it returns status 200, but makes the call to the app itself instead of proxy the request to the API.
I've tried both using "proxy" configuration in package.json as well as using "http-proxy-middleware". Both cases work with locally running app, but not deployed. Here is the configuration of the proxy:
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://XXXXXX.azurewebsites.net',
changeOrigin: true,
})
);
};
I suppose it's something related to the configuration of the node server used when I deploy to azure, but I don't have a clue what.
I've used the following tutorial for deployment: https://websitebeaver.com/deploy-create-react-app-to-azure-app-services
But as seen from content there is no proxy part in it.
After long troubleshooting I realize the issue was due to wrong understanding of the proxy configuration.
So I was not realizing the proxy configuration is respected only in debug mode and totally ignored into prod build. And of course while debugging the issue I was not realizing the Azure Deployment pipe was doing production build. So the resolution was to detect the production/dev on application layer and inject correct URL.
Here I hit another issue - process.env.NODE_ENV, which I was using to distinguish between development and production was undefined into my index.tsx - it was available in App.tsx and all its children, but not in index.tsx where my dependency container was initialized.
What resolved my issue is package called dotenv. Then I've just imported it into index.tsx and the process.env was available.
import * as dotenv from 'dotenv';

Change all api calls URL react when in production

I would like to know if it is possible to alter all the api calls made from my react app to my backend server. I used to have the static files to sit around in my project root directory, so when I made an api call with axios like await axios.get('/api/my-endpoint') it all worked fine and my requests were translated to GET https://www.example-url.com/api/my-endpoint. But now I am migrating to AWS EC2 and decided to serve static files from AWS S3. So now since the api is in a remote server all my api calls are broken. I need to replace all api calls to https://www.another-example-url.com/api/.... I know I can set the new URL in an environment variable, but that would force me to manually alter all of the api URLs in my front-end codebase. I would not be very happy to do this, since there are almost a thousand of them.
I tried to set the axios baseURL like so:
import axios from "axios";
const instance = axios.create({
baseURL: "www.another-example-url.com"
});
export default instance;
but then all the requests were translated to GET https://www.example-url.com/www.another-example-url.com/api/my-endpoint
Is there a lazy way of doing this? Or do I have to manually alter them all?
You can easily set this using "proxy" field in package.json file of client side. Just add following line
...
"proxy": "https://www.another-example-url.com",
...
edit: I almost forgot that you were asking for production build. So react-amazing-proxy is an alternate to create-react-app proxy which can have feature to use proxy in production build.
Another lazy way, if you are familiar with docker, would be to Dockerize your development built.

Nextjs api "pages/api" doesn't work on vercel server

Hello guys may you help me?
I'm trying to configure my fake API to create some personal projects but in my case, the method using the /pages/api folder only works for me in localhost when I deploy to the server on Vercel the project can't find my endpoints.
In my case I'm using the src/ folder method to develop my app and I don't know if this structure can cause problems with api folder.
One thing that I tried and worked is deploying to vercel using the api folder at the root of the application (out of /src folder) but the api stop working on localhost.
This structure works on localhost but doesn't work on server:
├───public/
├───src/
├───api/
├───pages/
...
next.config.js
package.json
This structure works on server but doesn't work on localhost:
├───api/
├───public/
├───src/
├───pages/
...
next.config.js
package.json
This is the method that I'm using to get data:
AXIOS API:
import axios from 'axios'
const api = axios.create({
baseURL: '/api/'
})
export default api
SWR HOOK:
import api from 'src/services/api'
import useSWR from 'swr'
function SwrFetchHook<Data = any, Error = any>(url: string) {
const { data, error } = useSWR<Data, Error>(url, async url => {
const response = await api.get(url)
return response.data
})
return { data, error }
}
export default SwrFetchHook
SWR callback:
const { data } = SwrFetchHook<INavItem[]>('categories')
I hope that I could explain, my question here is how is the best way to work with this feature because the /src folder is common to use with nextjs but I don't know if this is the real problem with the api folder.
Thanks!
Not 100% sure if this is the same issue. I had this warning in my build phase:
warn - Statically exporting a Next.js application via `next export` disables API routes. This command is meant for static-only hosts, and is not necessary to make your application static.
Make sure you are using the correct build command in out package.json scripts.
I'm my case:
"next build && next export" needed to be changed to "build": "next build"
Note: I removed && next export
This disabled the static export feature and allowed the use of pages/api when running yarn start note: yarn start relies on the build script within Vercel's build pipeline. So do not override the default settings unless it is needed.
Also normal Node/JS projects you can define a source folder in the scripts area ie "start": "<SOME_COMMAND> ./src"....but Next.js does this automatically so I do not think having an src file is the issue. I too have an src file in my project and it is a very common way (preferred way) of organizing your JS project. You shouldn't have to touch this if you are using next.
I tried deploying my app on digital ocean and it worked cuz vercel was not providing a server. I was not able to call my api from POSTMAN as well. Deployed it on digitalOcean and then it ran a server just like my localhost.

locally host firebase backend with react frontend together, for debugging

I am building a react website with firebase functions backend.
I'm using firebase serve to locally host the node.js backend that I connect to my react code through express API endpoints, and I am using react-scripts start to test my react frontend app.
all my get requests in my react app use /some endpoint to communicate with my firebase localserver. But they are running on different ports. firebase serves it on localhost:5000 while react live server hosts it at localhost:3000.
I tried many things and couldn't get any useful way to make this work. I at last added my react project as a subfolder in my firebase project and made the hosting public path at firebase.json to my react build directory. It works now but I always have to run npm run build on my react app on every change, to make it compile my app into the build directory, which is painfully slow.
What is the proper way to do this? debug react app and firebase backend together.
I finally enabled cross-origin-requests on my server using cors module
Serverside code
const cors = require("cors");
app.get("/test", (req, res) => {
return cors()(req, res, async () => {
res.send("working...");
});
});
Serverside code
And then adding a simple config file in the react side, to switch between debugging and deployed testing really helped.
config.js
var domain = "";
// domain = "http://localhost:5000";
export {domain}
then whenever I use apis in react, I simply comment/uncomment the second line to switch between local and deployed testing.
Then whenever I use APIs, I append `domain` before every url in all references, eg fetch requests
import { domain } from "config.js";
fetch(domain + "/int-search", ...
Then it worked fine running both the firebase backend and the react application on localhost, using firebase serve and npm start for my react app.

Redirect from http to https on localhost with create-react-app to test with Lighthouse

I have configured create-react-app to use https in my local development environment. I would now like to convert my React application to a progressive web app and I plan to use Lighthouse to check my status. I am running Lighthouse as a Chrome plugin, but I am having trouble with the part when it is checking if my HTTP requests are redirected to HTTPS. They are not.
I have been crawling through my node_modules and I have taken a look at webpack-dev-server that is bundled with create-react-app. I have tried to make some changes, but the best I have managed so far is that I have gotten "Too many redirects".
TL;DR: How can I configure create-react-app to redirect all requests from http to https on my local dev environment?
Here's the code from my create-react-app if you are having trouble with just the redirect part. I'm doing it manually since Heroku doesn't automatically handle it. But this actually needs to be handled on the server because it makes the app visibly load twice if it has to redirect to http. But for now, I'm redirecting in the constructor of my App component.
constructor(props, context) {
const url = window.location.origin
if (!url.includes('localhost') && !url.includes('https')) {
window.location = `https:${url.split(':'))[1]}`
}
}
For your purposes, you'd just need to take out the localhost part and make the new url a little differently (because of the port).
I'm using ramda here, but lodash also has a tail function you can use.
import { tail } from 'ramda
...
constructor(props, context) {
const url = window.location.origin
if (!url.includes('https')) {
window.location = `https:${tail(url.split(':')).join(':')}`
}
}
#Fmacs, for redirection of HTTP traffic to HTTPS, instead of using local dev-server, deploy your app on any environment like Heroku or Firebase. Firebase is very simple. I see that you also have other issues running the create-react-app that you created. I have explained how to do this in simple steps in a blog post with sample code in GitHub. Please refer to: http://softwaredevelopercentral.blogspot.com/2019/10/react-pwa-tutorial.html

Resources