0

I test an API with Postman and want to write a request with axios. This is what it looks like in Postman and it works fine.

enter image description here

This is my code in javascript:

  axios.post('http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token', null,  
  {   params: {
        grant_type : "password",
        username: "test",
        password: "password",
        client_id: "admin-cli"
      },
      headers: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
  }).then((response) => {
    console.log(response)
  }).catch((error) => {
    console.log(error)
  })

This results in the following error:

POST http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token?grant_type=password&username=test&password=password&client_id=admin-cli 400 (Bad Request)

I also tried to use curl, which also works:

curl -X POST   http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token  -H 'Content-Type: application/x-www-form-urlencoded' -d 'grant_type=password&username=test&password=password&client_id=admin-cli'

I guess there might be an error in my axios code, but I don´t know what might have gone wrong :-(

Data Mastery
  • 1,555
  • 4
  • 18
  • 60

2 Answers2

0

In your axios request you've send your data as parameters instead of form data. Have a look at this thread to see how to send form data: axios post request to send form data

Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27
0

You gotta send in the second param exactly what you're sending into params;

So the new request would be something like this:

  const data = {
    grant_type: "password",
    username: "test",
    password: "password",
    client_id: "admin-cli"
  }
  const url = 'http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token'
  axios.post(
    url, 
    data, // data in the second param
    {
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      }
    }).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
Felipe Malara
  • 1,796
  • 1
  • 7
  • 13