【发布时间】:2019-04-22 01:24:07
【问题描述】:
如何将此 paypal curl 命令转换为 Axios?
curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "client_id:secret" \
-d "grant_type=client_credentials"
我在 vue 中使用 vueAxios,因此是“this.”。
this.axios.post('https://api.sandbox.paypal.com/v1/oauth2/token',
{'Accept': "application/json", 'Accept-Language': "en_US",
'XXXXXX': 'XXXXX', // my paypal client ID and client secret
'grant_type':'client_credentials'}
)
.then( response => {
console.log("Response is: ", response);
})
.catch( error => {
console.log("Error is :", error);
});
我收到此错误:
Error is : Error: Request failed with status code 401
at createError (createError.js?16d0:16)
at settle (settle.js?db52:18)
at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)
我也试过这个(这似乎更好,但我仍然收到 400 错误):
this.axios({
method: 'POST',
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type':'application/x-www-form-urlencoded'
},
auth: {
username: '<XXXX My paypal client ID>',
password: '<XXXX My paypal secret>'
} ,
data: {
grant_type: 'client_credentials'
},
})
.then(function(response) {console.log(response);})
.catch(function(response) {console.log(response);});
更新 – 在对 cmets 进行一些帮助后,我尝试了以下代码,但 paypal 出现了 CORS 错误问题(我已经安装了一个 npm 包“cors”并且 cors 错误仍然存在(本地和部署时))。
这回答了我的问题,但是,as stated here,Paypal 似乎不允许直接来自浏览器的请求。
this.axios({
withCredentials: true,
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'post',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type':'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
},
data: { 'grant_type':'client_credentials' },
auth: {
username: 'XXXXXXXX',
password: 'XXXXXXXX'
}
})
相关文档:
CORS:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
VueAxios:https://www.npmjs.com/package/vue-axios
贝宝开发者:https://developer.paypal.com/docs/api/overview/#make-your-first-call
【问题讨论】:
-
没有关于 axios 的线索,但我很确定你混合了标头和有效负载。
-
是的。我不知道如何告知 axios 什么是 --header, --User 凭据是什么以及 --data 是什么...:/
标签: curl vue.js paypal httprequest axios