How can I convert following PHP Curl Request to 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);
I tried something like below. But getting 400 bad request error. How can I set CURLOPT_RETURNTRANSFER here. Or am I doing something wrong?
$.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);
}
});
I had done a mistake $('#response').html(data);
should be $('#response').html(JSON.stringify(data, null, " "));;
. Also keep in note Auth code works only once. To get a new access token use refresh token that you have got from the first response
$.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);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.