问题描述
我通常将 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}) });
}
我真的很想知道我在这里做错了什么,所以如果可能的话,我可以坚持使用一个包裹。
感谢任何反馈!
解决方法
这完全是我的错! 我没有意识到 API 调用实际上已经完成,而且我收到了一个 JSON 循环错误! 我只需要根据 API 调用的结果格式化数据。
res.status(200).json({'TokenData': token.data.access_token})