【问题标题】:How to make an encoded POST request using axios?如何使用 axios 进行编码的 POST 请求?
【发布时间】:2019-10-10 14:35:48
【问题描述】:

我正在尝试根据以下 API 请求示例在我的 reactjs 应用中创建 POST 请求:

示例 API 请求

curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token

我应该对标题中“Basic”后面的文本进行base64编码。

如何使用 axios 在 javascript 中创建此请求?这是我目前所拥有的:

async componentDidMount() {
        const encodedString = new Buffer('1ff56abe7792f426ea41a771d707d6690:1b2cca2dedd3949b0a6c5e1582446c9c5').toString('base64');

        const [initSpotResponse] = await Promise.all([
            axios.post('https://accounts.spotify.com/api/token', { headers: { 'Authorization': `Basic ${encodedString}` } })
        ]);
    }

如何包含“grant_type=client_credentials”部分?

【问题讨论】:

  • -d 代表data。所以,在第二个参数的对象中添加一个新对象data: {grant_type: 'client_credentials'}

标签: javascript reactjs post httprequest axios


【解决方案1】:

根据axios的README,这是POST请求的Request方法别名

axios.post(url[, data[, config]])

axios.post('https://accounts.spotify.com/api/token', 
    { data: { grant_type: ‘client_credentials’} }, 
    { headers: { 'Authorization': `Basic ${encodedString}` } }
)

你也可以这样做

const options = {
   url: ‘https://accounts.spotify.com/api/token', 
   method: 'POST',
   headers: { 'Authorization': `Basic ${encodedString}` },
   data: { grant_type: ‘client_credentials’} 
};

axios(options);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 2016-12-31
    • 2021-05-17
    • 2020-09-29
    • 1970-01-01
    • 2022-12-17
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多