繁体   English   中英

使用 Ajax 而不是 cUrl 执行 API 调用

[英]perform an API call with Ajax instead of cUrl

我有一个服务在我的网站的同一个域上运行,它公开了一个 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);
    });
        

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

我在这里缺少什么?

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

我通过添加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);
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM