【问题标题】:Particle Photon API: Getting costumer token works on Postman but not with axiosParticle Photon API:获取客户令牌适用于 Postman,但不适用于 axios
【发布时间】:2019-05-09 01:20:19
【问题描述】:

我正在开发一个结合了光子粒子的反应原生应用程序。 遵循 Two legged auth 的文档;在配置设备之前,我需要获取声明代码。

curl -X POST \
  https://api.particle.io/oauth/token \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&client_id=client_id&client_secret=clsecret&scope=customer%3Demail%40gmail.com'

当我使用 CURL 甚至邮递员发出请求时,我得到了想要的结果。但是当我在 react native (iOS) 中使用 axios 尝试此操作时,我总是收到以下错误:Invalid or missing grant_type parameter

下面的代码是我检索数据的 React Native 代码。正如你所看到的,我正在传递grant_type。

costumerToken() {
    const route = `${this.route}/oauth/token`;
    const headers = {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    const body = {
        "grant_type": "client_credentials",
        "client_id": this.clientId,
        "client_secret": this.clientSecret,
        "scope": `customer=${this.costumerEmail}`
    }
    console.log(route, headers, body);
    return axios.post(route, body, {headers: headers})
        .then(res => {
            return Promise.resolve(res);
        })
        .catch(err => {
            return Promise.reject(err.response);
        });
}

怎么了?

【问题讨论】:

    标签: react-native curl axios postman particle-photon


    【解决方案1】:

    当将Object 作为axios.post() 主体传递时,它将以JSON 形式发送,但粒子API 期望它为application/x-www-form-urlencodedAxios docs 更深入地探讨这个话题。要使其正常工作,您可以将代码更改为:

    customerToken() {
        const route = `${this.route}/oauth/token`;
        const headers = {
            "Accept": "application/json",
            "Content-Type": "application/x-www-form-urlencoded"
        }
        const body = new URLSearchParams();
        body.append("grant_type", "client_credentials");
        body.append("client_id", this.clientId);
        body.append("client_secret", this.clientSecret);
        body.append("scope", `customer=${this.costumerEmail}`);
        console.log(route, headers, body);
        return axios.post(route, body, {headers: headers})
            .then(res => {
                return Promise.resolve(res);
            })
            .catch(err => {
                return Promise.reject(err.response);
            });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-09
      • 2020-07-21
      • 2021-08-11
      • 2019-06-05
      • 2020-07-19
      • 2021-11-08
      • 2018-06-22
      • 1970-01-01
      相关资源
      最近更新 更多