[英]Send json as query body via rest call
我需要通過rest發送json的請求,客戶端(rest)的代碼是Node,服務器的代碼是golang。
身體看起來像下面
const query = "{\"query\":\"query {n result: application(id: \"fb7b5992-4d0a-4782-acb7-13ae6cc66102\") {n idn namen providerNamen descriptionn integrationSystemIDn labelsn status {n conditionn timestamptn }}n}\"}"
當我運行代碼時,我從服務器(go)收到以下錯誤,我使用
這是電話
const app = await fetch(`https://eway-auth-oauth.kh.de-arch.sho.ca.k8s-han.znd.com/dir/graphql`, {
method: 'post',
body: queryBody,
headers: {
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive',
'DNT': '1',
'Origin': 'https://eway-auth.kh.devx-ar.znd.com',
'authorization': 'Bearer xxxxxxxxxxxxxxx',
'tenant': '3e6rezae-38b5-46a0-b1ed-9ccee153a0am'
}
});
return {
ky: await app.json(),
}
錯誤
json body could not be decoded: invalid character 'z' after object key:value pair
z
是application(id:z....
這是我需要發送的數字。
知道我該如何克服這個問題嗎? 我掙扎了兩天
順便提一句,
當我嘗試它時,它的 curl 命令有效,當我將數據從終端復制到 js 變量query
時出現錯誤,不確定方法:(
更新
這是適用於我的 curl(上面的代碼不...)
curl `https://eway-auth-oauth.kh.de-arch.sho.ca.k8s-han.znd.com/dir/graphql` \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Connection: keep-alive' \
-H 'DNT: 1' \
-H 'Origin: https://eway-auth.kh.devx-ar.znd.com \
-H 'authorization: Bearer xxxxxxxxxxxxxxx' \
-H 'tenant: 3e6rezae-38b5-46a0-b1ed-9ccee153a0am' \
--data-binary '{\”query\":\"query {\n result: application(id: \"fb7b5992-4d0a-4782-acb7-13ae6cc66102\") {\n id\n name\n providerName\n description\n integrationSystemID\n labels\n status {\n condition\n timestampt\n \n}\n}\n}\"}'
\
--compressed
json 在您的字符串表示中未正確轉義。 特別是有必要轉義值中的引號並轉義反斜杠。 這意味着" => \"
或者,如果已經轉義,則為\" => \\\"
和例如\n => \\n
。
您可以將 json 直接分配給查詢。 在這種情況下,如果 json 無效,您的 IDE 通常已經在抱怨。
const query = {
"query": "query {\n result: application(id: \"fb7b5992-4d0a-4782-acb7-13ae6cc66102\") {\n id\n name\n providerName\n description\n integrationSystemID\n labels\n status {\n condition\n timestampt\n \n}\n}\n}"
};
您也可以使用'
來避免需要 escaping。 在大多數情況下,這不應該有所作為。 即使我不確定您在后端的解析器是否可以接受。
const query = {
"query": "query {\n result: application(id: 'fb7b5992-4d0a-4782-acb7-13ae6cc66102') {\n id\n name\n providerName\n description\n integrationSystemID\n labels\n status {\n condition\n timestampt\n \n}\n}\n}"
};
之后,您需要將其作為字符串傳遞給您的 http 請求:
const queryBody = JSON.stringify(query);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.