簡體   English   中英

將變量傳遞給graphql中的突變的正確語法是什么

[英]What is the correct syntax to pass variable into mutation in graphql

我有一個反應本地應用程序。

graphql中將變量傳遞到customerCreate的正確語法是什么?

const url = 'https://xxxx.myshopify.com/api/graphql';
const query = `
    var variable = {
          "input": {
          "email": "test@test.com",
          "password": "pass"
          }
    }

    mutation customerCreate($input: CustomerCreateInput!) {
      customerCreate(input: $input) {
        userErrors {
          field
          message
        }
        customer {
          id
        }
      }
    }
`;
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: query }),
})
.then(res => res.json())
.then(res => console.log(res.data));
.catch(err => {
    console.log('-- gql err --')
    console.error(err);
})

將變量傳遞給突變的一種方法可以是執行以下操作:

const url = 'https://xxxx.myshopify.com/api/graphql';
const query = `
    mutation customerCreate($input: CustomerCreateInput!) {
      customerCreate(input: $input) {
        userErrors {
          field
          message
        }
        customer {
          id
        }
      }
    }
`;
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 
        query: query,
        variables: {
           input: {
             email: "test@test.com",
             password: "pass"
           }
        }, 
    }),
})
.then(res => res.json())
.then(res => console.log(res.data));
.catch(err => {
    console.log('-- gql err --')
    console.error(err);
})

並且只需確保JSON.stringifyvariables對象必須匹配類型CustomerCreateInput

暫無
暫無

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

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