'I am facing an error net::ERR_ABORTED 401 (Unauthorized)

In my componentDidMount function I have a problem.

I'm facing error 401 in my Reactjs site, my username and password are correct.

componentDidMount() {
    console.log("Json Datalog") fetch('185.213.180.129:9900/cgi-bin/datalog.json', {
        'mode': 'no-cors'
      }, {
        method: "GET",
        credentials: 'include',
        headers: {
          'Authorization': 'Basic ' + btoa(this.state.deviceSettings.userName + ":" + this.state.deviceSettings.password),
        }
      }).then((response) => {
          console.log("Btoa Encryption::::: ", btoa(this.state.deviceSettings.userName + ":" + this.state.deviceSettings.password))


Solution 1:[1]

You're passing three arguments to fetch

effectively you are using fetch like

fetch('185.213.180.129:9900/cgi-bin/datalog.json', {
    mode: 'no-cors'
})

So your authentication header is not set at all

try this instead

fetch('185.213.180.129:9900/cgi-bin/datalog.json', {
    mode: 'no-cors',
    method: "GET",
    credentials: 'include',
    headers: {
      'Authorization': 'Basic ' + btoa(this.state.deviceSettings.userName + ":" + this.state.deviceSettings.password),
    }
  })

also, you need to understand what mode: 'no-cors' means - you will not have access to the response body if the request is not same origin - so forget reading the response as per the code in your comments (i.e. return response.json() ) - you will not get any access to the response using mode: 'no-cors'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1