{"type":"module","scripts":{"start":"node backend/server","server":"nodemon backend/server","client":"npm start --prefix frontend","dev":"concurrently \"npm run server\" \"npm run client\""},"devDependencies":{"concurrently":"^6.2.1","nodemon":"^2.0.12"}}
Environment Variables
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
importexpressfrom"express";importdotenvfrom"dotenv";importproductsfrom"./data/products.js";dotenv.config();constapp=express();app.get("/",(req,res)=>{res.send("API is running.....");});app.get("/api/products",(req,res)=>{res.json(products);});app.get("/api/products/:id",(req,res)=>{constproduct=products.find((p)=>p._id===req.params.id);res.json(product);});constPORT=process.env.PORT||5000;app.listen(PORT,console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));
React Frontend Fetching Products from Backend
Install Axios: a HTTP library to make request to backend
1
front % npm i axios
In HomeScreen.js, to request products from backend rather src/products.js
add products as component level state
state: component leve, global/application level
products will be global state via Redux
useState in functional components, no need constructors like class-based components
setProducts is function to change the state
useEffect React Hook to make a request to backend
use sync and await: returns a promise
pass an array of denpendencies
add a "proxy": "http://127.0.0.1:5000" in package.json we can look localhost:5000 rather than 3000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
importReact,{useState,useEffect}from"react";importaxiosfrom"axios";//import products from "../products";
constHomeScreen=()=>{const[products,setProducts]=useState([]);useEffect(()=>{constfetchProducts=async()=>{const{data}=awaitaxios.get("/api/products");setProducts(data);};fetchProducts();},[]);//return(...);
};