So I'm trying to move from REST to GraphQL but there's a minor thing that makes it a little bit harder is that queries eg
www.example.com?test=test
the query: { test: "test" }
is actually under body: { query: { test: "test" } }
in GraphQL. So I was wondering if there was some middleware or something that could move this back out.
I'm using body-parser
via
var bodyParser =
require("body-parser")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
Unless there's a specific reason you want to validate and execute the GraphQL document yourself, you should probably use an existing library for that. Two of the more popular solutions for express:
//express-graphql
const graphqlHTTP = require('express-graphql');
const { makeExecutableSchema } = require('graphql-tools');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true,
}));
app.listen(4000);
// apollo-server-express
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });
app.listen(4000);
You can also just use apollo-server
, which runs apollo-server-express under the hood.
const { ApolloServer, gql } = require('apollo-server');
// pass in a schema
const server = new ApolloServer({
schema
});
// or let Apollo make it for you
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen()
None of these solutions require you to include body-parser
and provide a ton of extra features out-of-the-box.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.