react-nativecurlaxiospostmanparticle-photon

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


I'm developing a react native application that combines a Photon Particle. By following the documentation of a Two legged auth; before configure a device I need to get a claim code.

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'

When I do the request using CURL or even postman I got the desired results. But when I tried this using axios inside react native (iOS), I'm always getting the following error: Invalid or missing grant_type parameter.

The code below is my React Native code that is retrieving the data. And as you can see, I'm passing the 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);
        });
}

What is wrong?


Solution

  • When passing an Object as axios.post() body, it will send it as JSON but the Particle API expect it to be application/x-www-form-urlencoded. Axios docs go more deeply into this topic. To make it work you could change the code to:

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