Girish chandra
Girish chandra

Reputation: 11

CORS policy problem in react js client side

I created a Formik login form and call to react js fetch method. Add cors in web api end and successfully run in Postman and jquery. How to call "token_type": "bearer", through react js? cors is also enabled in web api and also generate Token successfully. How to call this url https://localhost:44323/token through react js?

My code is

 onSubmit={(values) => {
                fetch('https://localhost:44323/token', {
                    method: 'POST',
                    header: { 'Content-type': 'application/json,multipart/form-data' },                    
                    data: JSON.stringify(values)
                })
                    .then(r => r.json())
                    .then(res => {
                        console.log(res)
                    });
            }}>

Error messages

Upvotes: 1

Views: 1152

Answers (1)

Gopinath
Gopinath

Reputation: 4937

The root cause of the problem can be found in the following error message shown:

"Access to fetch at https://localhost:44323/token from origin http://localhost:3000 has been blocked by CORS policy. No Access-Control-Allow-Origin header is present on the requested resource ...."


How to fix the problem?

The problem can be fixed in these ways:

1. Allow the origin (http://localhost:3000) on the server (Recommended)

This can be done by adding the following header to HTTP response on the server side:

Access-Control-Allow-Origin: http://localhost:3000

2. Send Fetch request in the 'no-cors' mode

This can be done by updating the fetch request as follows:

fetch( 'https://localhost:44323/token', 
       { 
           method: 'POST',
           mode: 'no-cors',
           headers: { 'Content-Type': 'application/json' },
           body: JSON.stringify(data)
       }
)
.then(response => {
        // Code for processing the response
      }
)
.catch((error) => {
        // Code for handling the error
      }
)

More information: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Upvotes: 1

Related Questions