2015-12-15 2 views
3

Я не могу подключиться к API Swiftype, преобразовая их метод cURL в Parse.httpRequest. Я получаю либо ошибку 400 с отсутствием объекта «document», либо информацию, чтобы связаться с Swiftype.Преобразование cURL из API Swiftype в Parse.httpRequest

Вот завиток, который работает:

curl -XPOST 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json' \ 
-H 'Content-Type: application/json' \ 
-d '{ 
    "auth_token":"xxx", 
    "document": { 
    "external_id": "1", 
    "fields": [ 
     {"name": "title", "value": "The Great Gatsby", "type": "string"}, 
     {"name": "author", "value": "F. Scott Fitzgerald", "type": "string"}, 
     {"name": "genre", "value": "fiction", "type": "enum"} 
    ] 
    } 
}' 

Примечание: я вошел ххх, чтобы скрыть фактический ключ я использую.

Parse.Cloud.httpRequest({ 
     method: 'POST', 
     url: 'https://xxx:@api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json', 
     header: 'Content-Type: application/x-www-form-urlencoded', 
     body:{'document': '{"external_id": "1","fields": []}'}, 
     success: function(httpResponse) { 
      console.log(httpResponse.text); 
      response.success(httpResponse.text); 
     }, 
     error: function(httpResponse) { 
      console.error('Request failed with response ' + httpResponse.text); 
      response.error(httpResponse.text); 
     } 
    }); 

Update 1: После некоторых проб и ошибок, следующий код проверяет подлинность, но возвращает этот параметр "документ" отсутствует

Parse.Cloud.httpRequest({ 
     method: 'POST', 
     url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json', 
     headers: 'content-type: application/json', 
     params: {auth_token:'xxxx'}, 
     body: '{"document":{}}', 
     success: function(httpResponse) { 
      console.log(httpResponse.text); 
      response.success(httpResponse.text); 
     }, 
     error: function(httpResponse) { 
      console.error('Request failed with response ' + httpResponse.text); 
      response.error(httpResponse.text); 
     } 
    }); 

Update 2: Это подтверждает

Parse.Cloud.httpRequest({ 
     method: 'POST', 
     url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json', 
     headers: 'content-type: application/json', 
     body:{auth_token:'xxx', 
      document: '{}'}, 
     success: function(httpResponse) { 
      console.log(httpResponse.text); 
      response.success(httpResponse.text); 
     }, 
     error: function(httpResponse) { 
      console.error('Request failed with response ' + httpResponse.text); 
      response.error(httpResponse.text); 
     } 
    }); 

Но когда я пытаюсь поставить объект в параметр документа, он дает мне ошибку «Can» t form encode Object ".

Parse.Cloud.httpRequest({ 
     method: 'POST', 
     url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json', 
     headers: 'content-type: application/json', 
     body:{auth_token:'xxx', 
      document: {'external_id': '1'}}, 
     success: function(httpResponse) { 
      console.log(httpResponse.text); 
      response.success(httpResponse.text); 
     }, 
     error: function(httpResponse) { 
      console.error('Request failed with response ' + httpResponse.text); 
      response.error(httpResponse.text); 
     } 
    }); 

Я попытался JSON.stringify (документ), но это не сработало, давая мне ошибку от «обратитесь в службу поддержки» Swiftype.

+0

По крайней мере, вы не отправляете правильный Content-Type, и вы не посылая auth_token в данные. – jcaron

+0

@jcaron изменил это, но не решил проблему. Я уточнил этот вопрос другими выводами. – Cyprian

+0

Почему вы не добавляете auth_token в тело, как в исходном запросе? – jcaron

ответ

1

И, наконец, получил его на работу. Проблема? Заголовок должен быть объект JSON

Здесь полностью функционирующий пример:

var bodyData = { 
    auth_token:"the_token", 
    document: { 
     external_id: "1", 
     fields: [{name: "title", value: "The Great Gatsby", type: "string"}] 
    } 
}; 


    Parse.Cloud.httpRequest({ 
     method: 'POST', 
     url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json', 
     headers: {'Content-Type': 'application/json'}, 
     body: bodyData, 
     success: function(httpResponse) { 
      console.log(httpResponse.text); 
      response.success(); 
     }, 
     error: function(httpResponse) { 
      console.error('Request failed with response ' + httpResponse.text); 
      response.error(httpResponse.text); 
     } 
    }); 
+0

Даже без символов ASCII в любом месте данных? Действительно ли вам нужно подтянуть тело вручную? – jcaron

+0

@jcaron, вы правы, мне это не нужно. Будет обновлен ответ. Спасибо за помощь! – Cyprian

+0

Комментарий, не относящийся к ASCII, должен был быть связан с необходимостью кодировки UTF-8. И я подумал бы, что вам не понадобится нить в любом случае. – jcaron

Смежные вопросы