I was scanning over the graphql docs to find express-graphql deprecated so I decided to implement the recommended graphql-html version:
this is my server.js:
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";
import http from "http";
import fs from "fs";
import path from "path";
const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);
const PORT = 4000;
var schema = buildSchema(
`
type Query {
hello: String
}
`
);
const root = {
hello: () => {
return "Hello, world!";
},
};
const handler = createHandler({ schema, rootValue: root });
const server = http.createServer((req, res) => {
if (req.url.startsWith("/graphql")) {
if (req.method === "OPTIONS") {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS, POST",
"Access-Control-Allow-Headers": "Content-Type",
});
res.end();
return;
}
if (req.method === "POST") {
handler(req, res);
} else if (req.method === "GET") {
const htmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
`;
res.writeHead(200, { "Content-Type": "text/html" });
res.end(htmlContent);
}
} else {
res.writeHead(404).end();
}
});
server.listen(PORT);
console.log(`Listening on port ${PORT}`);
and my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GraphQL Test</title>
</head>
<body>
<script>
// Simple GraphQL query using fetch
fetch('https://localhost:4000/graphql', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json; charset=urf8',
},
body: JSON.stringify({
query: `
query {
hello
}
`,
}),
})
.then(response => response.json())
.then(data => console.log('GraphQL Response:', data))
.catch(error => console.error('Error:', error));
</script>
</body>
</html>
However, I’m getting a status code of 415 in my browser and I’m not sure why. I tried adding the charset=utf8 header but that didn’t change anything.
1 Answer
You have a typo in your encoding urf8
should be UTF-8
, also since you’re not serving html from your express app you will need to set access control headers.
Here’s a fixed version of your code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GraphQL Test</title>
</head>
<body>
<script>
// Simple GraphQL query using fetch
fetch('https://localhost:4000/graphql', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
query: `
query {
hello
}
`,
}),
})
.then(response => response.json())
.then(data => console.log('GraphQL Response:', data))
.catch(error => console.error('Error:', error));
</script>
</body>
</html>
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";
import http from "http";
import fs from "fs";
import path from "path";
const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);
const PORT = 4000;
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = {
hello: () => {
return "Hello, world!";
},
};
const handler = createHandler({ schema, rootValue: root });
const server = http.createServer((req, res) => {
if (req.url.startsWith("/graphql")) {
if (req.method === "OPTIONS") {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS, POST",
"Access-Control-Allow-Headers": "Content-Type",
});
res.end();
return;
}
if (req.method === "POST") {
// Set CORS headers for GraphQL POST requests
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
handler(req, res);
} else if (req.method === "GET") {
const htmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
`;
res.writeHead(200, { "Content-Type": "text/html" });
res.end(htmlContent);
}
} else {
res.writeHead(404).end();
}
});
server.listen(PORT);
console.log(`Listening on port ${PORT}`);
8
-
tried all of the above, error persists
– Mathew6 hours ago
-
did you copy the code i just pasted ? how do you open index.html ?
– Reda Bourial6 hours ago
-
I'm using google chrome, clicking on it, I have exactly what you wrote
– Mathew6 hours ago
-
did you copy the code as is (you need the cors headers too) ? i hate to say this but it works on my machine.
– Reda Bourial6 hours ago
-
1
it seems I was missing the cors method, I don't get how that resolves a 415 status code
– Mathew6 hours ago