2017-04-06 149 views
0

以下請求適用於從GraphiQL發佈突變但不適用於我的應用程序的客戶端的情況。Graphql Mutation適用於Graphiql,但不適用於客戶端

控制檯中出現「POST http://localhost:3001/graphql 400(Bad Request)」錯誤。

const post = { 
    userId: store.user.id, 
    imageURLs: store.post.request.aws.imageURLs, 
    tags: store.post.tags, 
    link: store.post.link, 
}; 

const query = `mutation CreatePost($post: PostInput) { 
    createPost(post: $post) { 
    user, 
    tags, 
    imageURLs, 
    link 
    } 
}`; 

return fetch('/graphql', { 
    method: 'post', 
    headers: { 
    Accept: 'application/json', 
    'Content-Type': 'application/json', 
    }, 
    body: JSON.stringify({ 
    query, 
    variables: { 
     post, 
    }, 
    }), 
    credentials: 'include', 
}) 

有人知道發生了什麼事嗎?

+0

你在標題對象的Accept標題名稱周圍缺少引號? – sideshowbarker

回答

1

很多,你有什麼似乎就好了,但你必須輸入有效載荷和類型的突變作用:

mutation CreatePost($post: PostInput) { ... // CreatePost is not needed 

這裏是一個快速工作示例更好地說明您所需要的基因突變使用InputObject,並使用提取/節點擷取該請求:

fetching.js

let postUpdate = { 
    id: randomInt, 
    name: newPost.name 
}; 

let url = 'http://localhost:4001/graphql'; 
let query = `mutation ($postUpdate: PostInput) { 
    updatePost(postArgs: $postUpdate) { id, name } 
}`; 

let mutateInit = { 
    mode: 'cors', 
    method: 'post', 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify({ 
    query, 
    variables: { 
     postUpdate 
    }, 
    }) 
}; 

fetch(url, mutateInit) 
.then(res => res.text()) 
.then(out => { 
    console.log('Mutate response:', out); 
}); 
基於其他的例子在那裏

Schema.js

... 
const PostInput = new GraphQLInputObjectType({ 
    name: 'PostInput', 
    description: 'Mutation Input', 
    fields:() => ({ 
    num: {type: new GraphQLNonNull(GraphQLInt)}, 
    name: {type: new GraphQLNonNull(GraphQLString)} 
    }) 
}); 

const Mutation = new GraphQLObjectType({ 
    name: 'PostMutations', 
    description: 'Mutations for the Posts', 
    fields:() => ({ 
    updatePost: { 
     type: Post, 
     args: { 
     postArgs: { type: PostInput } 
     }, 
     resolve: (value, { postArgs }) => { 
     let post = Object.assign({}, postArgs); 
     return post; 
     } 
    } 
    }) 
}); 
... 

,似乎還有一些模糊的變量,可能會導致許多混亂的問題。通過這個例子,我們現在可以看到實際查詢中所需的不同變量。爲了使更多的意義了吧,讓我們來看看這個查詢被引用:

mutation ($<mutation_payload>: <Input Type>) { <mutation_function>(<function_argument_name>: $<mutation_payload>) { <returned fields> } }

只要這些都解決上述部分正確,抓取查詢應通過順利。如果他們不這樣做,你會發現自己遇到各種各樣的問題,如有效載荷未到達應該出現的位置時,「不能返回null,不能返回null」,以及抱怨GraphQL查詢本身的錯誤,因爲缺少某些輸入類型。

相關問題