簡體   English   中英

使用 graphql 發送我的文本區域的值

[英]sending value of my textarea with graphql

我希望你們都有美好的一天。 我正在編寫自己的個人網站,並且有一個部分可以聯系我。 我在這部分遇到的問題是,我試圖將我的客戶端 email 發送到我的 email,當我試圖通過 Graphql 將他們的消息發送到我的服務器時,我收到此錯誤

[
    {
        "message": "Syntax Error: Unterminated string.",
        "locations": [
            {
                "line": 3,
                "column": 123
            }
        ]
    }
]

我發送到服務器的請求是

'\n        mutation{\n            sendEmail(EmailInput: {name: "Test name", email: "Test@email.com", 
subject: "this is test subject", message: "\n         
   this is the first line \nthis is the second line\nwhen I have multiple lines I have these problem\n
            "}) {\n                success\n                message\n              }\n          }\n        '

我不知道如何解決它 我不知道為什么會出現此錯誤。 我使用 fetch 來發送我的代碼后端:

const emailMutationQuery = `
        mutation{
            sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}", message: "
            ${senderMessage.value}
            "}) {
                success
                message
              }
          }
          `;

const result = await fetch("http://localhost:2882/graphql", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        query: emailMutationQuery,
      }),
    });
    const convertedResult = await result.json();

GraphQL 支持變量,可用於獨立於查詢提供輸入數據。 這些變量只是一個單獨的 JSON 編碼的 object。這避免了試圖將輸入直接嵌入查詢中的句法困難(和潛在的安全風險)。

為此,您將編寫一個固定查詢,它聲明並使用變量,但不依賴於每個請求的輸入

const emailMutationQuery = `
mutation SendEmail($emailInput: SendEmailInput!) {
  sendEmail(EmailInput: $emailInput) {
    success
    message
  }
}
`;

然后您將創建第二個 object 包含變量。 頂級鍵與您在 GraphQL 操作行中聲明的內容匹配,其內容與對應的 GraphQL 輸入類型匹配。

const variables = {
  emailInput: {
    name: senderName.value,
    email: senderEmail.value,
    subject: senderSubject.value,
    message: senderMessage.value
  }
};

請注意,這是一個普通的 Javascript object,我們這里沒有引用或轉義任何內容。

現在當我們發出請求時,我們將查詢和變量一起發送

const result = await fetch("http://localhost:2882/graphql", {
  ...,
  body: JSON.stringify({
    query: emailMutationQuery,
    variables: variables
  })
});

消息內容中的換行符等內容將在變量塊中轉義,並正確傳遞到底層 GraphQL 引擎。

我實際上找到了解決方案,但請隨時在這里分享您的答案。 我為這個問題找到的解決方案是你必須對文本區域使用JSON.stringify() 你必須將你的textarea值傳遞給這個function,js會處理rest。我的代碼現在看起來像這樣

const emailMutationQuery = `
    mutation{
        sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}", 
        message:${JSON.stringify(senderMessage.value)}}) {
            success
            message
          }
      }
      `;

我希望這對你們有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM