Skip to content

ShubhamOS-cmd/backend-learn

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

backend learn

This is a video series on backend

notes

we setup frontend and backend and we connect them and they easily connect "CORS -> cross origin " to deal with this we have two way

  1. Proxy (Temporary )
  2. backend (Proper way)
useEffect(() => {
    fetch("http://localhost:4000/api/message")
      .then((res) => res.json())
      .then((data) => setMessage(data.message))
  },[]) 

by this in frontend we get message when we have to communicate a backend to a fronetnd then we assume that we are communicate at same domain , same port same domain means localhost , same port means backend run at which port is same at fronetnd run we have same localhost port 5173 for fronetnd and 4000 for backend now req res is change we have expected that we got a cors error how to resolve cors issue

1.proxy

so we have to set proxy setting in react.config.js

server:{
    proxy:{
      "/api" :{
        target: "http://localhost:4000",
        changeOrigin: true
      }
    }
  }

what this code is do -> when we send a request on /api then it automatically change the changeOrigin we send a req from localhost://5173 but this proxy make backend assume that this req come from localhost://4000 this called proxy and now we change our fetch "http://localhost:4000/api/message" to /api/message because our target is /api and then it automatically insert localhost://4000 on behind the /api

but this have some disadvantage this work only on devlopment time means when you devlop it's work but in case of production it fails

so we have to handle the proxy on backend

2. CORS

we have to handle the cors issue from backend backend tell that from which we accept data and from which we not accept data

app.use(cors(
    {
        origin: [
        "http://localhost:5173",
        "http://localhost:5174",
        "http://localhost:3000" // for serve
        // add production url
    ],
    credentials: true // when we have to accept cookie so we basically true marked,
    methods : ["GET" , "POST"], // it's for our application which methods accepted 
    llowedHeaders: ["Content-Type" , "Authorization"]
    }
));

by this only which origin are connect to backend which are in this array why this two origin some times when we start our fronetnd two times so basically fallback are happen that's that's why we add two this but it's only for dev not for production

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published