eolas/neuron/9445c5fd-135c-4b0b-a70c-7a6fd45d9d58/Using_GraphQL_with_Node.md

48 lines
1 KiB
Markdown
Raw Normal View History

2024-12-09 18:34:15 +00:00
---
tags: [graphql, node-js]
---
# Using GraphQL with Node.js
## Create a basic Express server
First we create a basic server in Node using Express:
```js
import express from "express";
app.get("/", (req, res) => {
res.send("Graph QL test project");
});
app.listen(8080, () =>
console.log("Running server on port localhost:8080/graphql")
);
```
## Add GraphQL as middlewear
Next we introduce GraphQL as a piece of Node.js
[middlewear](Middleware_in_NodeJS.md), with the
`app.use()` method.
```js
import { graphqlHTTP } from "express-graphql";
app.use(
"/graphql",
graphqlHTTP({
schema: schema,
rootValue: resolvers,
graphiql: true,
})
);
```
- `schema` is a reference to our GraphQL schema - the structure of the fields
that define our server.
- `rootValue` is a reference to our resolvers.
- `graphiql` is the GUI tool that will be served from the GraphQL endpoint at
`localhost:8080/graphql`. This tool enables us to interrogate our data using
the defined schema and see what data we would get back from frontend queries.