【问题标题】:Axios post request results in 400 - Bad requestAxios 发布请求导致 400 - 错误请求
【发布时间】:2021-03-31 00:59:38
【问题描述】:

我用 Postman 测试了一个 API,想用 axios 写一个请求。这就是它在 Postman 中的样子,并且运行良好。

这是我的 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 代码可能有错误,但我不知道可能出了什么问题 :-(

【问题讨论】:

    标签: vue.js axios


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您必须在第二个参数中准确发送您要发送到参数中的内容;

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-19
        • 2018-11-06
        • 2020-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-05
        • 1970-01-01
        相关资源
        最近更新 更多