我正在使用axios向Grapql编写一个简单的帖子示例。 完美的工作示例
let body = {
query: `
query {
game(id:"5c9beed4a34c1303f3371a38") {
_id
title
}
}
`,
variables: {}
}
axios.post("http://localhost:3344/graphql", body)
.then(res => {
console.log(res.data) // cool data from server
})
但是我想使用这种变量,我看到了一些例子,但是我无法使其工作
let body = {
query: `
query {
game(id: $id) { // IT SUPPOSE THE ID VARIABLE SHOULD BE INJECTED HERE
_id
title
}
}
`,
variables: {id: "5c9beed4a34c1303f3371a38"} // DECLARED VARIABLE ID
}
axios.post("http://localhost:3344/graphql", body)
.then(res => {
console.log(res.data) // 400 (Bad Request)
})
GRaphQl类型声明
type Query {
game(id: String!): Game!
}
根据评论,我也尝试了这一点。但仍然无法正常工作
let body = {
query: `
query {
Game($id: String!) {
game(id: $id) {
_id
title
}
}
}
`,
variables: {id: "5c9beed4a34c1303f3371a38"}
}
答案 0 :(得分:0)
您没有在查询中传递id变量,您必须像这样在查询级别定义
let body = {
query: `
query ($id: ID) {
game(id: $id) { // IT SUPPOSE THE ID VARIABLE SHOULD BE INJECTED HERE
_id
title
}
}
`,
variables: {id: "5c9beed4a34c1303f3371a38"} // DECLARED VARIABLE ID
}
注意:您的类型必须与ID或String之类的后端相同
答案 1 :(得分:0)
将类型声明更改为:
type Query {
game(id: ID!): Game!
}
然后:
const query = `query Game($id: ID!) {
game(id: $id) {
id
title
}
}`;
axios.post("http://localhost:3344/graphql",
body: JSON.stringify({
query,
variables: { id: "5c9beed4a34c1303f3371a38" },
})
).then(res => {
console.log(res.data)
})
答案 2 :(得分:0)
谢谢大家,我终于找到了解决问题的方法。
也许其他人可能需要它。
类型定义
type Query {
game(id: String!): Game!
}
查询应该是这样
let body = {
query: `
query Game($id: String!) { // notice the query Game structure
game(id: $id) {
_id
title
}
}`,
variables: {id: "5c9beed4a34c1303f3371a38"}
}
axios.post("http://localhost:3938/api/v1/graphql", body)
.then(res => {
console.log(res.data)
})