【问题标题】:How to add data to POST request using Axios?如何使用 Axios 向 POST 请求添加数据?
【发布时间】:2019-10-11 06:09:26
【问题描述】:

我正在尝试发出 POST 请求,但在我的 chrome 网络选项卡中收到以下消息:

{错误:“unsupported_grant_type”,…}错误:“unsupported_grant_type” error_description: "grant_type 必须是 client_credentials, 授权码或刷新令牌”

我一直在使用 Axios 进行 RESTful 调用,这是 POST 请求:

async componentDidMount() {
    const encodedString = 'blah'//some encoded string
    const [initSpotResponse] = await Promise.all([
        axios.post('https://accounts.spotify.com/api/token',
            { data: { grant_type: 'client_credentials' } },
            {
                headers: {
                    'Authorization': `Basic ${encodedString}`,
                    'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
                }
            }
        )
    ]);
}

我尝试了其他 StackOverflow 帖子中提到的各种方法,但似乎没有任何效果。有没有人有创建这样的 POST 请求的经验?我还没有看到关于这个问题的 axios 特定帖子 - 我应该放弃 axios(如果是,我应该切换到什么)?

【问题讨论】:

  • 您可以尝试 fetch,但您的身份验证似乎有问题。 client_credentials 应该是一个字符串还是你的意思是传递一个变量?
  • @cullanrocks client_credentials 应该是一个字符串,是的

标签: javascript reactjs post axios


【解决方案1】:

axios.post 接受数据对象 (axios.post(url[, data[, config]])) 作为第二个参数,使用 qs 序列化数据并尝试此操作,如 here 所述:

const qs = require('querystring');


async componentDidMount() {
    const encodedString = 'blah'//some encoded string
    const [initSpotResponse] = await Promise.all([
        axios.post('https://accounts.spotify.com/api/token',
            qs.stringify({ grant_type: 'client_credentials' }),
            {
                headers: {
                    'Authorization': `Basic ${encodedString}`,
                    'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
                }
            }
        )
    ]);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2022-11-02
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
相关资源
最近更新 更多