如何将这个curl请求转换为jquery请求


How would I turn this curl request into a jquery request?

我试图使用API,但它们的示例是curl,而不是javascript,这是我最熟悉的。以下是他们的例子:

$ curl http://visearch.visenze.com/uploadsearch '
   -d im_url=http://example.com/example-0.jpg '
   -d box=0,0,20,20 '
   -u access_key:secret_key

这是我对等效jquery请求的尝试,但它不起作用。

$.get("http://visearch.visenze.com/uploadsearch/im_url=http://example.com/example-0.jpg/box=0,0,20,20/u access :secret_key", function(data){...}); 
带有-d选项的cURL请求将请求作为POST请求发送(除非为GET请求指定了G修饰符),因此需要使用该格式。您还需要在beforeSend方法中设置标题:
$.ajax(
  'http://visearch.visenze.com/uploadsearch',
  type: 'post',
  data: {
    im_url: 'http://example.com/example-0.jpg',
    box: '0,0,20,20'
  },
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", "Basic ");
  }
);

如果使用$.ajax()$.get()是其简写),则可以使用usernamepassword参数(jQuery 1.7.2+)进行基本身份验证。如果需要该请求方法,则需要传递一个数据对象并指定POST。

$.ajax(
    url: 'http://visearch.visenze.com/uploadsearch',
    data: {
        im_url: 'http://example.com/example-0.jpg',
        box: '0,0,20,20',
    },
    username: 'access_key',
    password: 'secret_key',
    type: 'POST',
    success: function(data) {
        // ... your callback
    }
);

既然您已经在这个问题中标记了PHP,我将展示一个示例,说明您可能希望如何像Visenze API常见问题解答所建议的那样,将访问密钥等隐藏在后端包装器中:

1.创建一个PHP文件

<?php
$accessKey = 'access_key';
$secretKey = 'secret_key';
if (isset($_POST['im_url'], $_POST['box'])) {
    // Initialize the cURL request to ViSenze
    $ch = curl_init('http://visearch.visenze.com/uploadsearch');
    // We want to RETURN the result not output it
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set up the basic authentication settings
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, "$accessKey:$secretKey");
    // Define the post fields
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'im_url' => $_POST['im_url'],
        'box'    => $_POST['box']
    ]);
    // Do the request
    $result = curl_exec();
    curl_close($ch);
    // Output the results
    echo $result;
    exit;
}
echo 'Nothing posted to this script.';
exit;

2.使用jQuery调用该文件

$.post(
    'http://visearch.visenze.com/uploadsearch',
    {
        im_url: 'http://example.com/example-0.jpg',
        box: '0,0,20,20',
    },
    function(data) {
        // ... your callback
    }
);

通过这种方式,您的API凭据存储在PHP代码中,因此在查看页面源代码时不可见。