GraphQL: The schema is currently inaccessible

As someone new to GraphQL, I'm seeking your expert knowledge! I've encountered an issue where the Schema is not available in GraphiQL.

Here is the directory structure of my project:

https://i.sstatic.net/Bm9hi.png

Below are the contents of my files:

index.js

import express from "express";
import morgan from "morgan";
import config from "./config";

const app = express();

//Settings

//Middleware
app.use(morgan("dev"));
app.use(express.json());

//Routes
app.use(require("./routes/graphql.routes"));

//Starting server
app.listen(process.env.PORT || config.server.port, () => {
    console.log(config.server.name + " is listening on port " + config.server.port);
})

graphql.routes.js

import express from "express";
import GraphHTTP from "express-graphql";
import {PlayerModel} from "../models/player.model"; 
import {Schema} from "../schemas/schema"; 

const router = express.Router();

router.get("/graphiql", GraphHTTP({
    schema: Schema,
    pretty: true,
    graphiql: true
}));

module.exports = router;

player.model.js

import {DB} from "../db";
import Sequelize from "sequelize";
const PlayerModel = DB.db.define("tbl003_player", {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            notNull: true
        },
        name: {
            type: Sequelize.STRING,
            notNull: true,
            notEmpty: true
        },
        name_url: {
            type: Sequelize.STRING,
            notNull: true,
            notEmpty: true
        },
        language: {
            type: Sequelize.STRING,
            notNull: true,
            notEmpty: true,
            isIn: {
                args: [["sp", "en"]],
                msg: "Must be 'sp' or 'en'",
            }
        },
        twitter: {
            type: Sequelize.STRING,
            notEmpty: false
        },
        height: {
            type: Sequelize.FLOAT,
            isDecimal: true,
            notEmpty: false
        },...

player.schema.js

import {
    GraphQLObjectType,
    GraphQLNonNull,
    GraphQLID,
    GraphQLString,
    GraphQLFloat,
    GraphQLList
} from "graphql";
import {DateTime} from "../scalar/dateTime";


const Player = new GraphQLObjectType({
    name: "Player",
    description: "Player of basketball",
    fields: () => {
        return {
            id: {
                type: new GraphQLNonNull(GraphQLID),
                resolve(player){
                    return player.id
...                

I am struggling to understand this error. It seems like I have imported all modules correctly. What could be going wrong?

When I try to access http://localhost:3000/graphiql, I encounter this:

https://i.sstatic.net/aciKe.png

What am I missing here?

Edit I:

I observed in Chrome console that when the page loads, I receive the following messages:

https://i.sstatic.net/Eb7QU.png

The Morgan module in the console shows...

GET /graphiql 200 0.886 ms - 3868
POST /graphiql? 404 0.664 ms - 148
POST /graphiql? 404 2.034 ms - 148

Why does it show a 404 error for POST requests to /graphiql but works fine for GET requests? This has left me completely puzzled and confused.

Answer №1

Although this issue may be considered ancient, upon further review, I would recommend updating the following code snippet:

graphql.routes.js

import express from "express";
import GraphHTTP from "express-graphql";
import {PlayerModel} from "../models/player.model"; 
import {Schema} from "../schemas/schema"; 

const router = express.Router();

router.get("/graphiql", GraphHTTP({
    schema: Schema,
    pretty: true,
    graphiql: true
}));

router.post("/graphiql", GraphHTTP({
    schema: Schema,
    pretty: true,
    graphiql: true
}));

module.exports = router;

Replace it with the following:

import express from "express";
import GraphHTTP from "express-graphql";
import {PlayerModel} from "../models/player.model"; 
import {Schema} from "../schemas/schema"; 

const router = express.Router();

router.use("/graphiql", GraphHTTP({
    schema: Schema,
    pretty: true,
    graphiql: true
}));

module.exports = router;

Answer №2

Hooray, I've finally cracked the code! Adding the router.post function to my graphql.routes.js file was the missing piece of the puzzle, and now everything is up and running smoothly.

graphql.routes.js

import express from "express";
import GraphHTTP from "express-graphql";
import {PlayerModel} from "../models/player.model"; 
import {Schema} from "../schemas/schema";

const router = express.Router();

router.get("/graphiql", GraphHTTP({
    schema: Schema,
    pretty: true,
    graphiql: true
}));

router.post("/graphiql", GraphHTTP({
    schema: Schema,
    pretty: true,
    graphiql: true
}));

module.exports = router;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The combination of Ajax, JavaScript, PHP/HTML, and dynamic variables

Hey there, I'm currently working on a game development project and have encountered what seems to be a scope issue. The issue arises in my js file when a player clicks on the card they want to play: It starts in my js file:</p> <pre>&l ...

Refresh the page without submitting any information

Can anyone help me figure out how to refresh the page without triggering any posting when I press F5 or Ctrl+F5? I attempted the following code, but it doesn't seem to be working for me. $(document).ready(function(){ $(document).keyup(functio ...

Is all the javascript code from ajax.aspnetcdn.com/ajax/ currently malfunctioning? Causing issues with all external references? Since last

Since Friday evening I have been investigating issues with certain websites being unavailable and broken. I am a Verizon FIOS subscriber in Hudson County, NJ. Although I'm not an expert, my findings are intriguing so far: Firstly noticed sites like ...

Jquery's ajax function is failing to execute the server side function

I have a specific structure for my solution: My goal is to execute the recommendationProcess function from CTL_RateRecommendationDetails.ascx.cs in CTL_RateRecommendationDetails.ascx Therefore, I wrote the following code: $.ajax({ type: "POST", ...

Using JQuery's change function with a Button Group is a great way

I encountered an issue where my button group works with the on.click function but not with on.change. <div class="ui buttons"> <button class="ui button">Value 1</button> <button class="ui bu ...

Utilizing Vue to Transform Unicode Characters into HTML Elements

I have a scenario where an API response contains a Unicode string that needs to be displayed correctly in the view. Despite Vue treating it as a string and not automatically converting it to HTML, I believe JavaScript should handle the rendering process. ...

In the HTML code, the select option will show the value with an empty colored div and then

Is it possible to create an HTML select option that displays a value along with an empty color div? Can this be achieved using HTML, JavaScript, or jQuery? I have attached a png file for reference, and I want the output to look similar. <select> ...

Is there a way to prevent Express.js from triggering a file download in the browser?

I am attempting to preview a Word document file in the browser using an iframe: <iframe style="float:right;" src="/ViewerJS/#../demo/ohm2013.odp" width='400' height='300' allowfullscreen webkitallowfullscreen></iframe> (Fo ...

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...

Creating a jQuery thousands separator without losing the decimal accuracy with .toFixed(2)

I'm currently working on a Wordpress project where I need to create a pricing table using jQuery. One of the specific requirements is to format the numbers in thousands with spaces, like converting 1000 to 1 000. Although I have attempted various jQu ...

Transferring the date from an HTML input to a TypeScript file in Angular when the button

On my HTML page, I have two input fields for dates that need to be passed to the backend along with other parameters when a button is clicked. Here is the current setup: <input [owlDateTime]="dt1" placeholder="From a date" [value]="dateFrom.value"& ...

Ensure only one button per group is clicked when dynamically generating buttons with Vue.js

I am looking to create multiple questions with 4 answers each on a single website. The goal is to allow only one button to be clickable per question. Any suggestions on how to achieve this? new Vue({ el: '#app', data: { // data here ...

When Vue re-renders a single component, it can disrupt the rendering of other

I am faced with a dilemma involving two components that display varying information from the same data object stored in the state. Each component listens for store actions to detect changes and trigger a re-render. It is worth noting that Component A is n ...

Unveiling concealed data within ajax responses

On every cart change, I am attempting to reset my shipping estimator using ajax. The process works well across the entire page except for the shipping estimate section. Hidden values in use include: <input type="hidden" id="sendto" ...

Generating an Object Using HttpClient

When working with httpclient, you can specify the type for the get call and receive a struct of that object. For example. http.get<ProductData>("url:ressource:id").subscribe(x=> this.myObj = x) This means that myObj will only appear to ...

End the sessions of all users sharing the identical JWT token

Currently, I am utilizing React and Nodejs while incorporating JWT for user authentication. An issue has arisen where multiple users are simultaneously logged in with the same email address such as "[email protected]". Our objective now is ...

Validating Linkedin URLs with JavaScript for Input Fields

I've created a basic form with an input field for a LinkedIn URL. Is there a way to validate that this field only accepts valid LinkedIn URLs? Thank you! ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

I'm looking for some clarity on incorporating <SpeedInsights /> into NextJs14. Can anyone shed some light on

While working on my NextJs project, I attempted to integrate Vercel Speed Insight import { SpeedInsights } from "@vercel/speed-insights/next" <SpeedInsights /> An error related to hydration is being returned. I am looking for an explana ...

What steps can be taken to resolve an error in a recursive function used for adding HTML elements

Within this code snippet, the return statement is responsible for generating an HTML element based on the first element property of each object that is currently being iterated. It's worth noting that each object in the array can contain a children ar ...