[英]Convert PHP Curl Request to Javascript
How can I convert following PHP Curl Request to Javascript POST?如何将 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);
I tried something like below.我尝试了类似下面的方法。 But getting 400 bad request error.但是收到 400 bad request 错误。 How can I set CURLOPT_RETURNTRANSFER here.如何在此处设置CURLOPT_RETURNTRANSFER 。 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);
我犯了一个错误$('#response').html(data);
should be $('#response').html(JSON.stringify(data, null, " "));;
应该是$('#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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.