我正在开发一个结合 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
asaxios.post()
正文时,它会将其作为 JSON 发送,但粒子 API 期望它是application/x-www-form-urlencoded
. Axios 文档更深入地探讨了这个主题。为了使其工作,您可以将代码更改为:
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);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句