2016-10-26 50 views
0

是否有可能在graphql中傳遞正文查詢中的數據?像這樣如何在graphql中傳遞查詢參數

var name = formData.get('name'); 
    var email = formData.get('email'); 
    var message = formData.get('message'); 

    const resp = await fetch('/graphql', { 
     method: 'post', 
     headers: { 
      Accept: 'application/json', 
      'Content-Type': 'application/json', 
     }, 
     body: JSON.stringify({ 
      query: '{createPost (name: '+ name +' , email: '+ email +' , message: '+ message +') {id, statut}}', 

     }), 
     credentials: 'include', 
    }); 
    const { data } = await resp.json(); 
    if (!data || !data.createPost) throw new Error('Error'); 

    console.log(data.createPost) 

在查詢行中,我想要傳遞從提交表單中獲得的所有變量。 當我嘗試這一點,我得到這個錯誤

{ 


"errors": [ 
    { 
     "message": "Syntax Error GraphQL request (1:29) Expected :, found Name \"email\"\n\n1: {createPost(name: John Doe , email: [email protected] , message: blablabla) {id, statut}}\n        ^\n", 
     "locations": [ 
     { 
      "line": 1, 
      "column": 29 
     } 
     ] 
    } 
    ] 
} 

感謝您的幫助

回答

3

使用variables來編寫查詢,避免串建設。你可以免費獲得類型檢查!

我不精通在JavaScript,但我相信這將工作:

var name = formData.get('name'); 
var email = formData.get('email'); 
var message = formData.get('message'); 

const resp = await fetch('/graphql', { 
    method: 'post', 
    headers: { 
     Accept: 'application/json', 
     'Content-Type': 'application/json', 
    }, 
    body: JSON.stringify({ 
     query: 'query Q($name: String, $email: String, $message: String){createPost (name: $name, email: $email, message: $message) {id, statut}}', 
     variables: { 
      name: name, 
      email: email, 
      message: message 
     } 

    }), 
    credentials: 'include', 
}); 
const { data } = await resp.json(); 
if (!data || !data.createPost) throw new Error('Erreur sur l`envoi du message !'); 

console.log(data.createPost) 
0

下面是我工作;

const graphqlQuery = `{ 
     products { 
     id 
     title 
     images 
     } 
    }` 

const params = encodeURI(graphqlQuery) 

fetch('http://localhost:3001/?raw&query=' + params, { 
    method: 'post', 
    headers: { 
    "Content-Type": 'text/plain' 
    } 
}).then(function(response) { 
    console.log('response', response); 
    return response.json() 
})