首页 > 解决方案 > 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() });

标签: javascriptsyntaxoauth-2.0fetch

解决方案


感谢@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);
    }));

推荐阅读