将PHP Curl请求转换为Javascript

问题描述 投票:-1回答:1

如何将以下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错误的请求错误。如何在此处设置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);
                }             
        });
javascript ajax curl post http-post
1个回答
0
投票

我做错了$('#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);
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.