Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

google apps script - Invalid Argument with UrlFetch

I am trying to run a MongoLab (REST based access to MongoDB) query via Google Apps Script. The URL is generated from the logger is shown below
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":"Thu Dec 06 23:59:59 PST 2012"}}
When I type this in the browser, it works and gets me the response I am looking for. But running it via UrlFetchApp gives an "Invalid Argument" error. I see there are several posts along the same lines but didn't find an answer that worked for me. The Javascript code is as follows

//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);  

I tried encodeURIComponent, but it did not work - may be I was doing it incorrectly. Any suggestions as how I could overcome this issue?
Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Invalid Argument is coming because you are sending invalid characters in the URL parameter. You should encode the parameters first.

I modified your code and tried to run. But it still failed because of invaliD API key which is obvious. You may try this code with a valid API key.

//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);

Response which I am getting is

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."}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...