【问题标题】:perform an API call with Ajax instead of cUrl使用 Ajax 而不是 cUrl 执行 API 调用
【发布时间】:2021-02-28 14:52:20
【问题描述】:

我有一个服务在我的网站的同一个域上运行,它公开了一个 API。我已经设法使用 cUrl 调用 API,但我想将其移至一些 vanilla js/jquery。

我的实际代码是:

$postData = array(
    'userid' => $userid,
    'password' => $password,
    'email' => $userid
);

//creo utente base
$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, 'https://admin:password@xxx.com/cloud/ocs/v1.php/cloud/users');
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($postData));

我尝试过这样一个简单的 ajax 请求:

$.ajax({
    url: 'https://admin:password@xxx.com/cloud/ocs/v1.php/cloud/users',
    method: 'post',
    data: {userid:'a',password:'b',email:'c'},
    dataType: 'json'
}).done(function(data){
    //handle the results
});

或者这个:

$.ajax({
        url: 'https://mydomain/cloud/ocs/v1.php/cloud/users',
        beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "Basic "+btoa(admin:password));
        },
        method: 'post',
        data: {userid:'mario@mari.com',password:'Annapurna1',email:'mario@mari.com'},
        dataType: 'json'
    }).done(function(data){
        console.log(data);
    });
        

但我得到一个“unhautorized”的 401 错误。这意味着 url 中提供的凭据无效。但是,如果我使用 Postman 使用相同的 url 发出发布请求,它就会通过授权。

我在这里错过了什么?

【问题讨论】:

  • 如果是通过邮递员工作的,你可以使用邮递员的代码生成器直接为它生成js代码:D
  • 您确定您的类型一切正常吗? (字符串 VS 整数)
  • @singebatteur 代码中没有错别字。
  • @SamridhTuladhar 邮递员最终会得到我相同的代码。无论如何,问题在于 url 以及 jquery 如何发布它而不是在 ajax 请求语法中
  • 401 是非常明确的信息。使用邮递员时,您是使用基本授权还是仅发布登录凭据,导致您的代码不清楚?在您的第二次尝试中,当您尝试基本授权时,管理员和密码变量在哪里定义?

标签: javascript jquery ajax curl owncloud


【解决方案1】:

实际上我得到的错误完全是误导。

我通过添加contentType: 'application/x-www-form-urlencoded', 解决了这个问题,该contentType: 'application/x-www-form-urlencoded', 用于将参数发送到模拟表单的API。 即使错误消息与错误的身份验证(用于登录的用户名和密码)有关,而不是与传递给 API 的参数有关,添加此项也解决了问题。

所以我的最终代码是

$.ajax({
        url: 'https://mydomain/cloud/ocs/v1.php/cloud/users',
        beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "Basic "+btoa('admin:password'));
        },
        contentType: 'application/x-www-form-urlencoded',
        method: 'post',
        data: {userid:'john@gmail.com',password:'userpassword',email:'john@gmail.com'},
        dataType: 'json'
    }).done(function(data){
        console.log(data);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    相关资源
    最近更新 更多