【问题标题】:How to rewrite this cURL command to axios code如何将此 cURL 命令重写为 axios 代码
【发布时间】:2019-10-27 14:36:53
【问题描述】:

我需要调用 propublica API,他们使用 cURL 的调用示例:

  -H "X-API-Key: PROPUBLICA_API_KEY" 

如何在 axios 中重写它。

我试过了,但不起作用,得到一个未定义的响应。

    axios.get('"https://api.propublica.org/congress/v1/members/{house}/{FL}/current.json/X-API-Key/APIKEY '),

]).then(axios.spread((response1, response2) => {
    console.log(response1.data.url);

})).catch(error => {
    console.log(error);
}); ```

【问题讨论】:

    标签: node.js curl axios


    【解决方案1】:

    -H 选项是将选项作为标头传递,而不是作为查询参数或 URL 的一部分。您将不得不这样做:

    axios.get(url, { headers: { 'X-API-Key': headerKey } })
    

    【讨论】:

    • 我正在尝试这个:``` const axios = require('axios'); axios.all([ axios.get('"api.propublica.org/congress/v1/115/senate/members.json"', { headers: { 'X-API-Key': "9q67HMZ2ly0hOrXWjT9l31WN6TiGuh7XrkBl1vC"} }) ]) .then(axios.spread((response) => { console.log(response.data.url); })).catch(error => { console.log(error); }); ``` 仍然未定义
    • Mario-Fsairtun 提出的建议是正确的方法。也使用标题而不是参数。
    【解决方案2】:

    使用 RESTClient Extension for firefox,这对我有用:

    https://api.propublica.org/congress/v1/116/senate/members.json
    

    在标头 X-API-Key:my-personal -key 中。 所以使用 axios,你可以使用:

    let url = 'https://api.propublica.org/congress/v1/116/senate/members.json';
    axios.get(url,
      { 
        headers: { 
          'X-API-Key': headerKey 
        }
      }
    )
    .then (res=>console.log(res))   
    .catch(err => console.log(err));
    

    【讨论】:

    • 欢迎您sairtun。很高兴为您提供帮助。
    【解决方案3】:

    这是有效的,感谢您的回答。

    const axios = require('axios');
    
    axios.request({
        url: "https://api.propublica.org/congress/v1/members/house/FL/current.json",
        headers: { 'X-API-Key': "API-KEY" },
        method: 'get'
    }).then(response => {
        // console.log(response.data.url);
        console.log(response.data)
    }).catch(error => {
        console.log(error);
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 1970-01-01
      • 2016-08-19
      • 2019-06-30
      • 2021-10-08
      • 2017-12-31
      • 2012-05-10
      • 2013-05-23
      • 2019-03-25
      相关资源
      最近更新 更多