let server = app
.use(cors())
.use(router.routes())
.use(router.allowedMethods())
.listen(9000);
console.log(server is starting at port ${server.address().port});
let app = new Koa();
const apollo = new ApolloServer({ typeDefs, resolvers });
apollo.applyMiddleware({ app });
...
console.log(apollo: ${apollo.graphqlPath});
open http://localhost:9000/graphql
![screen shot 2018-10-24 at 7 24 22 pm](https://user-images.githubusercontent.com/1457904/47427340-9e0bc980-d7c2-11e8-9bd2-d554c24bdd78.jpg)
你可以通过{ hello }查询,服务根据query然后通过resolvers进行解析。
# GraphQL client for React
`yarn add apollo-boost react-apollo graphql --save`
import ApolloClient from "apollo-boost";
import gql from "graphql-tag";
solution
frontend
backend (api only)
几个原因
koa
startup
app.js
let app = new Koa(); let router = new Router();
router.get('/', async (ctx) => { ctx.body = "hello world"; });
router.get('/ctx', async (ctx) => { ctx.body = ctx; })
let server = app .use(cors()) .use(router.routes()) .use(router.allowedMethods()) .listen(9000); console.log(
server is starting at port ${server.address().port}
);"scripts": { "start": "nodemon --delay 2 app.js" },
const mongoose = require('mongoose') mongoose.connect('mongodb://user:pwd@ds243325.mlab.com:43325/m365', {useNewUrlParser: true}); const Meeting = mongoose.model('meetings', {name: String});
router.get('/', async (ctx) => { ctx.body = await Meeting.find({}); });
const { ApolloServer, gql } = require('apollo-server-koa');
const typeDefs = gql
type Query { hello: String }
;const resolvers = { Query: { hello: () => 'Hello world!', }, };
let app = new Koa(); const apollo = new ApolloServer({ typeDefs, resolvers }); apollo.applyMiddleware({ app }); ... console.log(
apollo: ${apollo.graphqlPath}
);import ApolloClient from "apollo-boost"; import gql from "graphql-tag";
const client = new ApolloClient({ uri: "http://localhost:9000/graphql" });
componentDidMount() { client.query({ query: gql
{ hello }
}).then(result => { this.setState({ hello: result.data.hello }) }); }import { ApolloProvider } from "react-apollo"; import ApolloClient from "apollo-boost";
const client = new ApolloClient({ uri: "http://localhost:9000/graphql" });
let app = (
);
{data.hello}
}}