2012-12-07 30 views
4

我試圖通過Google Apps腳本運行MongoLab(基於REST的MongoDB訪問)查詢。從記錄器生成的URL如下所示
https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q= {「created_on」:{「$ gte」:「Thu Dec 06 00:00:00 PST 2012」,「$ lt」:「Dec Dec 06 23:59: 59 PST 2012「}}
當我在瀏覽器中輸入它時,它可以正常工作並獲得我期待的回覆。但是,通過UrlFetchApp運行它會出現「無效參數」錯誤。我看到有幾個帖子沿着相同的路線,但沒有找到適合我的答案。 Javascript代碼如下UrlFetch的無效參數

//start and end are JS date objects 
var query = { created_on : {'$gte': start, '$lt' : end} }; 
var url = MONGO_LAB_URLS.MAIN + "&q=" + Utilities.jsonStringify(query); 
Logger.log("Query URL : " + url); 
var response = UrlFetchApp.fetch(url); 

我試過encodeURIComponent,但它沒有工作 - 可能是我做的不正確。有什麼建議可以解決這個問題?
謝謝。

回答

4

無效的參數即將到來,因爲您在URL參數中發送無效字符。您應該首先對參數進行編碼。

我修改了你的代碼並試圖運行。但它仍然因失敗API密鑰而失敗,這是顯而易見的。您可以使用有效的API密鑰嘗試此代碼。

//start and end are JS date objects 
    MONGO_LAB_URLS = 'https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q='; 
    var start = 'Thu Dec 06 00:00:00 PST 2012'; 
    var end = 'Thu Dec 06 23:59:59 PST 2012'; 

    var query = { created_on : {'$gte': start, '$lt' : end} }; 
    var url = MONGO_LAB_URLS + encodeURIComponent(Utilities.jsonStringify(query)); 
    Logger.log("Query URL : " + url); 
    var response = UrlFetchApp.fetch(url); 
    Logger.log(response); 

響應這我得到的是

Request failed for https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q=%7B%22created_on%22%3A%7B%22%24gte%22%3A%22Thu%20Dec%2006%2000%3A00%3A00%20PST%202012%22%2C%22%24lt%22%3A%22Thu%20Dec%2006%2023%3A59%3A59%20PST%202012%22%7D%7D returned code 400. Server response: { "message" : "Please provide a valid API key."} 
+0

這工作。謝謝你的幫助Waqar。 – Kris