Search code examples
reactjscorsaccess-tokenrequest-headers

In REACT, GET http:/xxxx 401 (Unauthorized)/ (CORS) : For "localhost"


Trying to call the below API by using axios.getmethod. I've bypassed the CORS by using the Moesif CORS google extension.
The API required the tokens in order to pull the result by using POSTMAN.

Insert the valid tokens: Getting the CORS error although the CORS extension is enabled.
CORS Error
Without the tokens: Getting the 401 Unauthorized with CORS extension enabled as well.
401 Unauthorized

I'm sort of confused, is it either my token unauthorized issue or the CORS issue here? could someone please advise? However, if I called the other API that does not require the token I'm able to get the result without any issue with the CORS extension enabled.

Sharing my example codes here:

const tokenStr = 'abc1234'; // example
const config = {
  headers: { Authorization: `Bearer ${tokenStr}` }
};

let dcqoapi = 
"http://quote.dellsvc/v3/quotes?number=" + Quote + "&version=" + Version;

  const calldcqoapi = () => { //assign a variable for a call function
        Axios.get (dcqoapi,config).then(
          (response) => {
          console.log(response);
        })

  };

Solution

  • The issue was resolved via disabling the web security from Chrome. Here are the below actions I've taken: [WORKS FOR LOCALHOST]

    1. Create a shortcut on your desktop.
    2. Right-click on the shortcut and click Properties.
    3. Edit the Target property.
    4. Set it to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession"
    5. Open Google chrome (You should see the message "disable-web-security" on top of the page)
    6. Run your app
    7. Copy your localhost URL and paste it to the Chrome
    8. It works perfectly now for calling the API with headers tokens.

    By doing the above steps, we had fully bypassed all the security including the CORS. Hence, Moesift CORS is no longer required.
    As I'm using POSTMAN for calling the API with the Headers.
    Some little changes from my codes, instead of putting 'Bearer' and I've removed it.
    The 'bearer' is for authorization. Headers are not considering bearer tokens, it's just a key so we shouldn't enter the 'bearer' for the POSTMAN headers.

    let config = {
    
      headers: { Authorization: 'PlACE YOUR TOKENS HERE'}
    
    };
    
    let dcqoapi =
    "https://quote.dellsvc/v3/quotes?number="+ Quote +"&version=" + Version // set DCQO API
    
    const calldcqoapi = () => { //assign a variable for a call function
        Axios.get (dcqoapi,config).then(
          (response) => {
          console.log(response);
    })
    
    };