所以我正在开发一个项目,希望我使用 GraphQL 来创建我的 API。我还使用 NodeJS 和 Express。通常我只是在express中设置一个端点并从客户端使用axios调用它。在服务器的端点内,我可以从 req.body 获取信息并用它做我想要的事情。我在哪里可以使用 GraphQL 以相同的方式操作数据?感觉我所做的只是查询数据,而不是像我想要的那样操作数据并将其发送回来。
这是我所拥有的:
架构 graphql:
import GraphQLDate from 'graphql-date';
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema,
GraphQLList,
GraphQLNonNull,
} = require('graphql');
const SecretMessage = new GraphQLObjectType({
name: 'secretMessage',
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
message: { type: GraphQLString },
expirDate: { type: GraphQLDate },
}),
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
secretMessage: {
type: SecretMessage,
args: {
name: { type: GraphQLString },
},
resolve(parVal, args) {
return `${args.name}test`;
},
},
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
});
我的 Node 服务器:
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import webpack from 'webpack';
const config = require('../webpack.config.js');
const expressGraphQL = require('express-graphql');
const schema = require('./schema.js');
const compiler = webpack(config);
const port = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(express.static('css'));
app.use(express.static('images'));
app.use('/graphql', expressGraphQL({
schema,
graphiql: true,
}));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../public/src', 'index.html'));
});
app.get('#', (req, res) => {
console.log('Pound hashtag works');
});
app.post('passphrase', (req, res) => {
console.log('passphrase tag works');
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../public/src', 'index.html'));
});
app.listen(port, (error) => {
if (error) {
console.log('This is the express error: ', error);
} else {
console.log('Express is listening on port: ', port);
}
});
axios({
method: 'post',
url: '/graphql',
data: JSON.stringify({
query: `secretMessage(name: "${this.state.name}") {name}`,
}),
}).then((response) => {
console.log('This is the response from the axios call: ', response);
}).catch((error) => {
console.log('This is the error from the main axios call: ', error);
});
当我对/graphql 进行 axios post 调用时,我只是收到 400 bad request 错误。
字符串插值旁边的“测试”是我只是想看看我是否可以操纵那里的数据。但我不知道如何在 postman 中测试它。有什么想法吗?
最佳答案
假设您使用 express-graphql
或类似的中间件,您的 GraphQL 端点将可以使用 POST 和 GET 请求进行访问。
使用 POST:
- 更改请求网址以匹配您服务器的 GraphQL 端点
- 确保请求方法是 POST,而不是 GET
- 在
正文
下,选择x-www-form-urlencoded
- 添加
查询
作为键
,并将整个查询字符串添加为值
- 如果您有任何变量,请添加
variables
键并将它们作为值
(它们需要是格式正确的 JSON)。
使用 GET:
- 更改请求网址以匹配您服务器的 GraphQL 端点
- 确保请求的方法是 GET
- 将
查询
添加为键
,并将整个查询字符串添加为Params
下的值
- 如果您有任何变量,请添加
variables
参数并将它们作为值
(它们需要是格式正确的 JSON)。
或者...
如果您正在构建 GraphQL 服务器,您可能会发现公开 Graphi QL 端点来测试查询要容易得多。您可以阅读更多相关信息here .
它已融入到 graphql-server-express
(请参阅文档 here )和 express-graphql
(文档 here )中。
编辑:就操作请求中的数据而言:是的,您可以在解析器函数中读取请求并指定要返回的数据。但是,每个 resolve()
函数都与一个特定字段绑定(bind),该字段返回特定类型。查询和突变本身只不过是“根查询”或“根突变”类型上的字段,这就是为什么它们也具有解析函数。
您的 secretMessage
查询解析为 secretMessage
类型,但您将其解析为字符串。如果您尝试运行该查询,结果将始终返回 null。相反,如果您希望它返回一个具有您根据传入的参数修改的 name 属性的对象,您可以这样做:
resolve(parVal, args) {
return { name: `${args.name}test` };
},
现在,如果您执行如下查询:
query MyQuery {
secretMessage(name: "John") {
name
}
}
你应该回来:
{
"data": {
"secretMessage": {
"name": "Johntest"
}
}
}
您还可以为 name
字段指定一个解析器,以达到相同的效果。如何以及何时使用解析器取决于您想要实现的目标。更详细的解释超出了这个问题的范围,但我鼓励您深入研究官方文档并更好地了解解析器的工作原理。然后,您可以在此处提出后续问题(如果尚未提出问题!)。
关于javascript - 我是否错误地使用了 GraphQL?我不知道它如何向我发送回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46027527/