2016-04-03 157 views
0

我正在嘗試從Node創建對uClassify API的請求。我無法弄清楚什麼是錯的,我寫的代碼:通過節點請求向uClassify API發出請求

const req = JSON.stringify('Hello, my love!'); 
    const options = { 
    body: req, 
    method: 'POST', 
    url: 'https://api.uclassify.com/v1/uClassify/Sentiment/classify', 
    headers: { 
     'Content-Type': 'application/json', 
     Authorization: 'MyKey' 
    } 
    }; 

    request(options, (error, response, body) => { 
    if (!error) { 
     callback(response); 
    } 
    }); 

我得到如下回應:

statusCode: 400, 
body: "{"statusCode":400, 
     "message": "Error converting value \"Hello, my love!\" to 
     type 'UClassify.RestClient.TextPayload'. Path '', line 1, position 17."}" 
     }" 

有一個在the documentation爲JS沒有明確的指示,我不知道是否我在我的request代碼中正確地在cURL中實現了他們的示例。

網址-X POST -H 「授權:令牌YOUR_READ_API_KEY_HERE」 -H 「內容類型:應用程序/ JSON」 --data 「{\」 文本\ 「:\」 我很高興今天 「}}」https://api.uclassify.com/v1/uClassify/Sentiment/classify

回答

1

在你的Node.js代碼中你的身體不正確(但在你的cURL中你使用了正確的身體)。 uClassify期望具有屬性texts的對象。 更改您的node.js代碼中的正文如下:

const req = JSON.stringify({ texts: ['Hello, my love!'] }); 
const options = { 
    body: req, 
    method: 'POST', 
    url: 'https://api.uclassify.com/v1/uClassify/Sentiment/classify', 
    headers: { 
    'Content-Type': 'application/json', 
    Authorization: 'MyKey' 
    } 
}; 

request(options, (error, response, body) => { 
    if (!error) { 
    callback(response); 
    } 
}); 
+0

謝謝!我其實試圖設置'texts'屬性,但顯然我搞砸了語法。還有一件事,我必須以'Authorization:Token MyKey'形式傳遞令牌。乾杯! –