【问题标题】:Node.js: Axios vs Fetch using x-www-form-urlencodedNode.js:使用 x-www-form-urlencoded 的 Axios 与 Fetch
【发布时间】:2021-06-27 22:11:42
【问题描述】:

我通常使用 Axios 来处理我的 API 请求,但由于某种原因,我在使用 Axios 访问外部 API 时遇到了问题。

另一方面,Fetch 可以很好地处理这个特定的请求。

我正试图找出我在这里做错了什么。

Axios:

async function getToken(req, res) {

  const apiCreds = {
        'grant_type' : 'client_credentials',
        'client_id' : xxxxxxxxxxxx,
        'client_secret' : xxxxxxxxxxxx,
        'scope' : 'PublicAPI'
   }

  const header = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
  }
    
  const token = await axios.post(`${process.env.URL}`,qs.stringify(apiCreds),header)
  
  res.status(200).json({'TokenData': token})
}

我尝试将qs.stringify 添加到对象主体,但这也不起作用。

获取:

async function getToken(req, res) {
    
    const apiCreds = {
        'grant_type' : 'client_credentials',
        'client_id' : xxxxxxxxxxx,
        'client_secret' : xxxxxxxxxxxxx,
        'scope' : 'PublicAPI'
    }

    fetch(`${process.env.VS_URL}`, {
            method: 'post',
            body:    qs.stringify(apiCreds),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        })
        .then(res => res.json())
        .then(json => { res.status(200).json({'TokenData': json}) }); 
            
            
}

我真的很想知道我在这里做错了什么,所以如果可能的话,我可以坚持使用一个包。

感谢任何反馈!

【问题讨论】:

    标签: node.js axios http-headers fetch x-www-form-urlencoded


    【解决方案1】:

    这完全是我的错! 我没有意识到 API 调用实际上已经通过并且我收到了 JSON 循环错误! 我只需要根据 API 调用的结果格式化数据。

    res.status(200).json({'TokenData': token.data.access_token})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多