Particle Photon API:获取客户令牌适用于 Postman,但不适用于 axios

Particle Photon API: Getting costumer token works on Postman but not with axios

我正在开发一个结合了 Photon Particle 的 React Native 应用程序。 按照双足认证的文档;在配置设备之前,我需要获取申请代码。

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);
        });
}

怎么了?

当将 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);
        });
}