具有UrlFetch的无效参数 [英] Invalid Argument with UrlFetch
问题描述
我正在尝试通过Google Apps脚本运行MongoLab(基于REST的MongoDB访问)查询.从记录器生成的URL如下所示
https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey = XXXXXXXXXXXXXXXX& q = {"created_on":{"$ gte":"Phu Dec 06 00:00:00 PST 2012","$ lt":"2012年12月6日星期四23:59:59 PST"}}
当我在浏览器中键入此命令时,它将起作用并获得所需的响应.但是通过UrlFetchApp运行它会出现无效参数"错误.我看到有几条相同的帖子,但没有找到对我有用的答案.Javascript代码如下
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);
我尝试了encodeURIComponent,但是没有用-可能是我做错了.有什么建议可以解决这个问题?
谢谢.
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.
推荐答案
即将出现无效参数,因为您正在URL参数中发送无效字符.您应该先对参数进行编码.
Invalid Argument is coming because you are sending invalid characters in the URL parameter. You should encode the parameters first.
我修改了您的代码并尝试运行.但是它仍然由于无效的API密钥而失败,这很明显.您可以使用有效的API密钥尝试此代码.
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);
我得到的回应是
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."}
这篇关于具有UrlFetch的无效参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!