我是第一次尝试 GraphQL,我正在尝试POST
一些数据并在 MongoDB 数据库中创建一个新文档。
我已经定义了一个“Office”模型。这是文档的样子:
{
fax: 4161234567,
image: {
full: 'http://placehold.it/1400x800',
large: 'http://placehold.it/1000x600',
medium: 'http://placehold.it/700x400',
small: 'http://placehold.it/400x200'
},
location: {
address: '123 Street Name',
city: 'Toronto',
country: 'Canada',
countryCode: 'CA',
state: 'ON',
suite: null,
zip: 'H6L 1C8'
},
phone: 4161234567,
slug: 'office-name',
title: 'Office Name'
}
我在服务器上使用 Node 和 Express。这是我的突变:
const schema = buildSchema(`
type Image {
full: String
large: String
medium: String
small: String
}
type Location {
address: String
city: String
country: String
countryCode: String
state: String
suite: String
zip: String
}
input ImageInput {
full: String
large: String
medium: String
small: String
}
input LocationInput {
address: String
city: String
country: String
countryCode: String
state: String
suite: String
zip: String
}
type Office {
_id: String
fax: Float
image: Image
location: Location
phone: Float
slug: String
title: String
}
type Mutation {
createOffice(fax: Float, image: ImageInput, location: LocationInput, phone: Float, slug: String, title: String): Office
}
`);
客户端,我有这个:
fetch('http://localhost:4300/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: 'mutation { createOffice(fax: 5041234567, image: {full: "http://placehold.it/1400x800", large: "http://placehold.it/1000x600", medium: "http://placehold.it/700x400", small: "http://placehold.it/400x200"}, location: {address: "456 Wilcox Ave.", city: "Montreal", country: "Canada", countryCode: "CA", state: "QC", suite: 2300, zip: "H3A 0A8"}, phone: 5047654321, slug: "my-office", title: "My Office" { phone } }'
}),
})
.then((res) => {
return res.json();
})
.then((res) => {
console.log(res.data);
});
我收到这些错误:
Syntax Error: Expected Name, found {"
我认为这是我的语法问题:
body: JSON.stringify({
query: 'mutation { createOffice(fax: 5041234567, image: {full: "http://placehold.it/1400x800", large: "http://placehold.it/1000x600", medium: "http://placehold.it/700x400", small: "http://placehold.it/400x200"}, location: {address: "456 Wilcox Ave.", city: "Montreal", country: "Canada", countryCode: "CA", state: "QC", suite: 2300, zip: "H3A 0A8"}, phone: 5047654321, slug: "my-office", title: "My Office" { phone } }'
})
我究竟做错了什么?