javascript - 如何将curl转换为javascript post请求

标签 javascript ajax curl stripe-connect

如何将此curl代码转换为适用于所有浏览器的javascript post请求

curl https://connect.stripe.com/oauth/token \
-d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \
-d code="{AUTHORIZATION_CODE}" \
-d grant_type=authorization_code

经过一些研究和审查这个答案 Convert command curl to javascript ,我发现我可以这样实现请求

$.ajax({
 url: "https://connect.stripe.com/oauth/token",
beforeSend: function(xhr) { 
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,

success: function (data) {
console.log(JSON.stringify(data));
},
  error: function(){
 console.log(error)
} 
});

如何添加 client_secret、code 和 grant_type?

最佳答案

不完全清楚您的要求。 但这里有一些片段可以使用
发出此帖子请求 JQuery

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://connect.stripe.com/oauth/token",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
  },
  "data": {
    "client_secret": "sk_test_f7PKXx5NRBFG5r41nTrPT7qB",
    "code": "\"{AUTHORIZATION_CODE}\"",
    "grant_type": "authorization_code"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

vanialla JavaScript:

var data = "client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB&code=%22%7BAUTHORIZATION_CODE%7D%22&grant_type=authorization_code";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://connect.stripe.com/oauth/token");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);

关于javascript - 如何将curl转换为javascript post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49383982/

相关文章:

javascript - 在单击事件上运行 AJAX 调用 - 使用 React.js

ajax - 何时启用 CORS 是安全的?

ruby-on-rails - Rails Typhoeus curl 问题

javascript - 如何在 react-native 中编写特定于 flavor 的代码?

javascript - jQuery/JavaScript - trim 两个元素之间的空白/制表符?

python - 将错误链接到 WTForms FieldLists 中的正确字段

c++ - VS2012 : 'nmake' is not recognized as an internal or external command

ruby - 用于 curl/libcurl 的最佳 ruby 绑定(bind)/gem

javascript - react : filter array: Can I work with elements that didn't pass the test?

javascript - 使用公司代理服务器的 Web 应用程序性能