简体   繁体   中英

What is the best way to enable CORS in React Application?

There are different ways to make a REST call in react- eg

 axios.post('link', JSON.stringify(data1),
          {
              headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
          .then(response => {
              console.log("res:", response)
          })
          .catch(err =>{
              console.log(err)
          })
        }

OR

 fetch('http://localhost:8080/feedbacks/addfeedback', {
               method: 'post',
               headers: {
                   'Content-Type': 'application/json',
                   'Access-Control-Allow-Origin' : '*'
               },
               body:body

What is the most effiecient way to enable CORS. Is there any other way that I can do this either in frontend or backend?

It depends on what HTTP library you are using.

See What is difference between Axios and Fetch? .

I usually use Axios, next what i do is creating a global instance and configuring Axios once.

export const api = axios.create({
    baseURL: '_URL_',
    timeout: 1000,
    withCredentials: false,
    responseType: 'json',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*' // whatever you want
    }
});

// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;

Also i'm enabling CORS on my server side application.

Thanks to @henrik123 for good explanation:

The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM