[英]Convert PHP Curl Request to Javascript
如何將 PHP Curl 請求轉換為 Javascript POST?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code',
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close ($ch);
我嘗試了類似下面的方法。 但是收到 400 bad request 錯誤。 如何在此處設置CURLOPT_RETURNTRANSFER 。 還是我做錯了什么?
$.ajax({
type: 'POST',
url: "https://accounts.google.com/o/oauth2/token",
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: {
client_id: client_id,
client_secret: client_secret,
code: code,
redirect_uri: redirect_uri,
grant_type: grant_type,
},
success: function (data) {
$('#response').html(data);
},
error: function (e) {
$('#response').html(e.responseText);
}
});
我犯了一個錯誤$('#response').html(data);
應該是$('#response').html(JSON.stringify(data, null, " "));;
. 另請注意,身份驗證代碼只能使用一次。 要獲取新的訪問令牌,請使用您從第一個響應中獲得的刷新令牌
$.ajax({
type: 'POST',
url: "https://accounts.google.com/o/oauth2/token",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
crossDomain:true,
cache : true,
dataType: 'json',
data: {
client_id: client_id,
client_secret: client_secret,
code: code,
redirect_uri: redirect_uri,
grant_type: grant_type,
},
success: function (data) {
$('#response').html(JSON.stringify(data, null, " "));;
},
error: function (e) {
$('#response').html(e.responseText);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.