javascript - Fetch API 调用的响应 400
问题描述
我正在尝试使用 JavaScript 的 Fetch API 进行调用以生成 OAuth 令牌,但我不断收到 400 响应代码,我不知道为什么。我将密钥和秘密写入控制台以验证它们的值,并使用 cURL 进行了相同的 API 调用(具有我预期的响应)。我的语法有小问题吗?
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret
}).then(r => { response = r.json() });
解决方案
感谢@Arun 关于添加 Content-Type 的建议,我现在得到了正确的响应。
此外,对于任何其他使用 petfinder API 的 JavaScript 新手来说,这是我用来从响应中提取令牌的链:
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret
}).then(response => response.json().then(data => ({
data: data,
status: response.status})
).then(function(res) {
console.log(res.status, res.data.access_token);
}));
推荐阅读
- xml - 如何使用python将文本转换为xml?
- python - 如何使用python将DataFrame中的列插入具有可变列数的数据库表的新列中
- machine-learning - 不平衡类的随机抽样
- python - 从具有多个表的网页中获取python中的数据
- java - 在 Gradle JVM 中设置 JAVA_HOME 以在 Eclipse 中打开 JDK11 而不会干扰系统环境变量
- javascript - 总结 React 道具中对象数组中的所有“分数”值
- spring-boot - 为什么在RestController中Get方法起作用时post方法不起作用?
- python - python 正则表达式替换所有以“:”开头的单词,下一个字符是字母
- jquery - 位置绝对 TD 在可见后留下空白空间
- html - 在引导程序中对齐列