Google App脚本中的API发布请求无效 [英] API Post request in Google App Script not working
问题描述
我设法通过Postman发出了API POST请求,但是为Google App Script修改后,它就无法工作.我认为这可能与 body
格式有关,我无法在GAS中复制 new URLSearchParams()
对象(我发送的是JSON)./p>
谢谢.
邮递员(正在工作)-JavaScript提取
var myHeaders = new Headers();myHeaders.append("Content-Type","application/x-www-form-urlencoded");var urlencoded = new URLSearchParams();urlencoded.append("client_id","XXXX");urlencoded.append("client_secret","XXXX");urlencoded.append("grant_type","client_credentials");var requestOptions = {方法:"POST",标头:myHeaders,正文:urlencoded,重定向:关注"};fetch("https://apigateway.criteo.com/oauth2/token",requestOptions).then(response => response.text()).then(结果=> console.log(结果)).catch(错误=> console.log('错误',错误));
CURL
curl --location --request POST'https://apigateway.criteo.com/oauth2/token'\--header'Content-Type:application/x-www-form-urlencoded'\--data-urlencode'client_id = XXXX'\--data-urlencode'client_secret = XXXX'\--data-urlencode'grant_type = client_credentials'
我的GAS版本错误:(
function getCostAU(){var myHeaders = {接受":"application/json","Content-Type":"application/x-www-form-urlencoded"};var myPayload = {"client_id":"XXXX","client_secret":"XXXX","grant_type":"client_credentials""};var requestOptions = {方法:"POST",标头:myHeaders,正文:myPayload,重定向:关注",};var url ="https://apigateway.criteo.com/oauth2/token";var result = JSON.parse(UrlFetchApp.fetch(url,requestOptions).getContentText());var access_token = result.access_token;};
问题:
-
body
是不是options
参数中的有效键.您应该改用payload
. -
重定向
不是options
参数 -
当前,
URLSearchParams
在应用程序脚本中不受支持.
解决方案:
-
将
body
更改为payload
-
重新创建
payload
对象作为查询字符串.例如,payload:{x:1,y:2}
应该更改为x = 1& y = 2
.
摘要:
- 有效载荷对象以查询参数:
函数objectToQueryParams(obj){返回 (Object.entries(obj).map(([[k,v])=>`$ {encodeURIComponent(k)} = $ {encodeURIComponent(v)}`).join('&'));}const myPayload = {"client_id":"XXXX","client_secret":"XXXX","grant_type":"client_credentials"};console.log(objectToQueryParams(myPayload));
- 有效的
requestOption
:
const requestOptions = {/** @请参阅https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)*/方法:"POST",标头:myHeaders,有效负载:objectToQueryParams(myPayload),//已修改//或只是有效负载:myPayload将按照下面的注释中所述工作//重定向:关注",//已删除followRedirects:正确};
- 完整脚本:
/**模拟UrlFetchApp库*/const UrlFetchApp = {提取:()=>({getContentText:()=>'{"access_token":"jghlfdjlfwqwXjogsfshbkgetrwuguerjyrcyfxuux =="},}),};getCostAU();//调用函数//模拟结束函数getCostAU(){const myHeaders = {接受:"application/json",内容类型":应用程序/x-www-form-urlencoded",};const myPayload = {client_id:"XXXX",client_secret:"XXXX",grant_type:"client_credentials",};函数objectToQueryParams(obj){返回Object.entries(obj).map(([[k,v])=>`$ {encodeURIComponent(k)} = $ {encodeURIComponent(v)}`).join('&');}const requestOptions = {/** @请参阅https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)*/方法:"POST",标头:myHeaders,有效负载:objectToQueryParams(myPayload),//已修改//或只是有效负载:myPayload将按照下面的注释中所述工作//重定向:关注",//已删除按照重定向:true,};const url ='https://apigateway.criteo.com/oauth2/token';const result = JSON.parse(UrlFetchApp.fetch(url,requestOptions).getContentText());const access_token = result.access_token;console.log(access_token);}
I managed to do the API POST request through Postman but once modified for Google App Script it doesn't work. I think it might be related to the body
format, I can't replicate the new URLSearchParams()
object in GAS (I'm sending a JSON I believe).
Thanks.
Postman (working) - JavaScript Fetch
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "XXXX");
urlencoded.append("client_secret", "XXXX");
urlencoded.append("grant_type", "client_credentials");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://apigateway.criteo.com/oauth2/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
CURL
curl --location --request POST 'https://apigateway.criteo.com/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=XXXX' \
--data-urlencode 'client_secret=XXXX' \
--data-urlencode 'grant_type=client_credentials'
My faulty GAS version :(
function getCostAU() {
var myHeaders = {"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"};
var myPayload = {"client_id" : "XXXX",
"client_secret" : "XXXX",
"grant_type" : "client_credentials"};
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: myPayload,
redirect: 'follow',
};
var url = "https://apigateway.criteo.com/oauth2/token";
var result = JSON.parse(UrlFetchApp.fetch(url, requestOptions).getContentText());
var access_token = result.access_token;
};
Issues:
body
is not a valid key inoptions
argument. You should usepayload
instead.redirect
is not a valid key inoptions
argumentCurrently,
URLSearchParams
is not supported in apps script.
Solution:
Change
body
topayload
Re-create the
payload
object as a query string. For example,payload:{x:1,y:2}
should be changed tox=1&y=2
.
Snippet:
- Payload object to query params:
function objectToQueryParams(obj) {
return (
Object.entries(obj)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&')
);
}
const myPayload = {"client_id" : "XXXX",
"client_secret" : "XXXX",
"grant_type" : "client_credentials"};
console.log(objectToQueryParams(myPayload));
- Valid
requestOption
:
const requestOptions = {
/**@see https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)*/
method: 'POST',
headers: myHeaders,
payload: objectToQueryParams(myPayload),//modified
//or just payload: myPayload will work as mentioned in the comments below
//redirect: 'follow',//removed
followRedirects: true
};
- Full script:
/**Mock UrlFetchApp library*/
const UrlFetchApp = {
fetch: () => ({
getContentText: () =>
'{"access_token":"jghlfdjlfwqwXjogsfshbkgetrwuguerjyrcyfxuux=="}',
}),
};
getCostAU(); //call function
//Mock end
function getCostAU() {
const myHeaders = {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
};
const myPayload = {
client_id: 'XXXX',
client_secret: 'XXXX',
grant_type: 'client_credentials',
};
function objectToQueryParams(obj) {
return Object.entries(obj)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
}
const requestOptions = {
/**@see https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)*/
method: 'POST',
headers: myHeaders,
payload: objectToQueryParams(myPayload), //modified
//or just payload: myPayload will work as mentioned in the comments below
//redirect: 'follow',//removed
followRedirects: true,
};
const url = 'https://apigateway.criteo.com/oauth2/token';
const result = JSON.parse(
UrlFetchApp.fetch(url, requestOptions).getContentText()
);
const access_token = result.access_token;
console.log(access_token);
}
这篇关于Google App脚本中的API发布请求无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!