-1

My API GET request is working in Postman, but not in React.JS / the browser. I have to pass in a username and password at the beginning of the URL to gain access to the API information, which again works fine in Postman, but not React/browser.

My GET request looks like this:

http://username:password@mywebsite.com:4040/api/stuff/stuff2

It works in Postman, but when I do an axios GET request in React, in the console.logs it looks like the username:password portion of the request has been removed and I get an error code saying I'm unauthorized.

Here's the React code:

    getList = () => {
        axios
            .get('http://username:password@mywebsite.com:4040/api/stuff/stuff2')
            .then(res => {
                console.log(res)
                this.setState({
                    list: res.data
                })
            })
            .catch(err => console.log(err))
    }

Do you know how to make the GET request work in React?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Page COW
  • 515
  • 13
  • 31

1 Answers1

1

You're trying to use basic access authentication this works in Postman because Postman isn't doing an AJAX request, browsers simply do not let you pass that information in an AJAX request URL.

Previously answered here!

You can pass auth as an option to your axios.get call like this:

axios.get(
  'http://mywebsite.com:4040/api/stuff/stuff2', 
   {
     auth: {
       username: 'username',
       password: 'password'
     }
   }
)
SeedyROM
  • 2,203
  • 1
  • 18
  • 22