Axios 发布请求结果为 400 - 错误请求

时间:2020-12-21 08:46:19

标签: vue.js axios

我用 Postman 测试了一个 API,想用 axios 写一个请求。这就是 Postman 中的样子,而且工作正常。

enter image description here

这是我在 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)
  })

这会导致以下错误:

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)

我也尝试使用 curl,它也有效:

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'

我猜我的 axios 代码可能有错误,但我不知道可能出了什么问题:-(

2 个答案:

答案 0 :(得分:0)

在您的 axios 请求中,您将数据作为参数而不是表单数据发送。 查看此线程以了解如何发送表单数据:axios post request to send form data

答案 1 :(得分:0)

你必须准确地发送你发送到 params 的第二个参数;

所以新的请求应该是这样的:

  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)
    })