Home > front end >  Cannot set username and password as default auth in axios in React
Cannot set username and password as default auth in axios in React

Time:10-07

I am new to ReactJS and trying to set the default auth values in API calls. I am using basic auth for login and this is the code that I'm using:

axios.defaults.auth.username = process.env.REACT_APP_AUTH_USERNAME
axios.defaults.auth.password = process.env.REACT_APP_AUTH_PASSWORD
axios.defaults.headers["user_token"] = JSON.parse(localStorage.getItem("uid"))

When the server is started (yarn start), is throws this error:

fakebackend_helper.js:700 
        
Uncaught TypeError: Cannot set properties of undefined (setting 'username')
at ./src/helpers/fakebackend_helper.js (fakebackend_helper.js:700:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:62:1)
at ./src/store/DropDownList/saga.js (reducer.js:28:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:62:1)
at ./src/store/sagas.js (reducers.js:59:1)
at options.factory (react refresh:6:1)

When I use auth like this it works perfectly.

axios
    .post(url.UPDATE_PROGRESS_NOTE_BY_STAFF, data, {
      headers: {
        user_token: JSON.parse(localStorage.getItem("uid")),
      },
      auth: {
        username: process.env.REACT_APP_AUTH_USERNAME,
        password: process.env.REACT_APP_AUTH_PASSWORD,
      }
    })
    .then(response => {console.log(response)})
    .catch(err => {console.log(err)})
}

in axios.defaults there is also auth.username and password option to create them as default that's why i am using this instead of like axios.defaults.headers.common["Authorization"] = "Basic" token but didn't find the right way to set value.

Please guide me on this.

CodePudding user response:

The AxiosDefaults type defines auth as

auth?: AxiosBasicCredentials;

meaning it is potentially undefined (and probably is by default).

You simply need to set the entire auth object

axios.defaults.auth = {
  username: process.env.REACT_APP_AUTH_USERNAME,
  password: process.env.REACT_APP_AUTH_PASSWORD,
}
  • Related