Error 400 occurs when using mutation, yet the same mutation successfully executes in GraphiQL

After following tutorials and attempting to learn GraphQL with React and Express, I've hit a roadblock. The mutation works fine when I test it in graphiql but fails when called from my client.

Client Code:

async addBook(params) {
    var title = params["title"];
    var author = params["author"];
    var src = params["src"];

    var mutation = `
        { addBook($author: String!, $title: String!, $src: String!) {
            addBook(author: $author, title: $title, src: $src) {
                id
                title
            }
        } 
    }`;

    const res = await fetch(this.apiUrl, {
        method: 'POST',
        mode: 'cors',
        headers: new Headers({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        }),
        body: JSON.stringify({
            query: mutation,
            variables: {author: author, title: title, src: src}
        }),
    });
    if (res.ok) {
        const body = await res.json();
        console.log(body.data);
        return body.data;
    } else {
        throw new Error(res.status);
    }
}

Schema Code:

const typeDefs = `
    type Book {
        id: ID!
        author: String!
        title: String!
        src: String!

    }

    type Query {
        Books: [Book]
    }

    type Mutation {
        addBook(author: String, title: String, src: String): Book
    }
`;

Resolver

Mutation: {
    addBook: (root, args) => {
        const newBook = {id: Books.length+1, author: args.author, title: args.title, src: args.src};
        Books.push(newBook);
        return newBook;
    },
},

The error

{"errors":[{"message":"Syntax Error GraphQL request (2:25) Expected Name, found $\n\n1: \n2:             { mutation ($author: String!, $title: String!, $src: String!) {\n                           ^\n3:                 addBook(author: $author, title: $title, src: $src) {\n","locations":[{"line":2,"column":25}]}]}

My "database" is a .js file containing a const books

I can successfully send queries and receive results, but mutations prove to be more challenging.

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

It appears that graphiql is being lenient with the syntax you provided, but it may not be entirely correct. A more accurate format would likely resemble the following:

let mutation = `
    mutation AddBook($author: String!, $title: String!, $src: String!) {
        addBook(author: $author, title: $title, src: $src) {
            id
            title
        }
    } 
`;

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

Positioning Material-UI Drawer within a designated div: A comprehensive guide

I am currently incorporating the Material-UI React Drawer into my project. Is there a way to restrict the drawer to a specific section of the page instead of it taking up the entire window? I attempted setting an absolute position for the root component in ...

Tips for managing the mongo client in NodeJS

Exploring the concept of managing the mongo client in a node application has led me to consider creating a new client for each collection retrieval. Here is an example implementation: const getCollection = (collectionName) => { return MongoClient.connec ...

What is the reason behind the necessity for a React class component to always invoke super(props) within its constructor function?

I recently came across a tutorial from reactjs.org that mentioned the importance of calling the base constructor with props in class components. However, further research led me to a StackOverflow answer suggesting that super() can be used instead of super ...

My PayPal script (and all other JavaScript) was rendered dysfunctional by Onsen UI

I've been gradually incorporating Onsen UI into my existing web app. Currently, my home page file (index.jade) includes a splitter for navigation within the app. The splitter loads a NodeJS route that renders the requested page in jade. Everything wo ...

Mongoose and Mocha detected an absence of listeners; error in validation

Currently, I am in the process of setting up a unit test for the POST function within my express app. The Mongoose schema that I have in place is quite simple, consisting of two fields, with one being marked as required. During testing with mocha, when I ...

Utilizing express mysql authentication to connect to preexisting WordPress user accounts

Currently working on developing a login PWA using React and Node for an established WordPress site. Any suggestions on how to verify the password provided by the user against the encrypted WordPress password created when the account was initially set up? ...

"Encountered an issue with Next-Auth session returning as undefined in getServerSideProps using NextJS version 13.2

When inspecting the code below, session is found to be undefined upon logging from the client side after being transferred from getServerSideProps. import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[. ...

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

"Encountered a 'net::ERR_HTTP2_PROTOCOL_ERROR' while trying to load a resource for a React app following an upgrade to Visual Studio 2019 version 16.10.0

Since upgrading to VS 16.10.0 (and then 16.10.1) Community Edition, a React website is no longer functioning within Visual Studio/IIS Express. Interestingly, the exact same code runs perfectly when deployed to an Azure app service. Upon loading the home p ...

Encountering issues with npm installation due to the errno -2 error

I encountered errors while attempting to install npm, as indicated below: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.5.0 npm ERR! argv "/Users/bunniehsieh/.nvm/versions/node/v4.1.0/bin/node" "/Users/bunniehsieh/.nvm/ ...

Unable to establish a connection with the Azure Knowledge Base generated by Language Studio and implement the provided code snippet:

const { ActionTypes } = require("botbuilder"); const { FAQMaker } = require("botbuilder-ai"); // Insert your own Azure Insight Base values here const insightBaseId = "**************************1d38"; const endpointToken = &qu ...

I'm in the process of constructing a create-next-app and I need to retrieve data from a web API. However, I'm unsure of the best place to securely store the API key

I am working on building a create-next-app that will retrieve data from the News Catcher API and display it within my application. I have obtained an API key to access the News Catcher API. However, I am unsure of where to securely store the API key and h ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

The overflowing issue with the Nextjs Tailwind Marquee Component is causing a display

I've recently developed a unique nextjs/tailwind component. This component displays an isometric marquee that scrolls horizontally. However, I'm facing an issue where the content overflows to the right and causes the page to become horizontally s ...

Optimizing your webpack bundle by dynamically splitting directories with the SplitChunks plugin

In an attempt to organize my React code, which was created using create-react-app, I am utilizing the splitChunks plugin in the following manner: The current structure of my components (JSX) is as follows: services serviceA ...

Switch out the icons within a return statement in JavaScript

Help! I have 5 empty star icons (<StarBorderIcon/>) displayed for a product on the material-ui website. I need to replace them with filled star icons (<StarIcon/>) based on the rating entered into a function. I attempted to use replace(), but i ...

The file or directory does not exist: .. ode_modules.staging@types eact-transition-group-96871f11package.json

I'm facing an issue while attempting to run a React project in VS2013. I followed a tutorial from here and initially, everything seemed to be working fine. However, when I tried to customize the project by adding more packages to the package.json fil ...

React Native: Transferring data from one screen to a component and across to a different screen with stack navigator

I am facing an issue with my stack navigator setup on the home screen, where I have a jobs component rendering with a name title. When the user clicks on this title, I want to navigate them to a job description screen while passing along the title data as ...

What is the best way to provide a service to a React <Route>?

I am looking to pass some data to my React Routes using Provider and my other stores. <Router> <Routes> <Provider store={store}> <Route path="/" element={HomePage} /> </Provider> <P ...

Tips for uploading a jpg image to the server using react-camera

My objective is to transfer an image captured from a webcam to a Lambda function, which will then upload it to AWS S3. The Lambda function appears to work during testing, but I'm struggling to determine the exact data that needs to be passed from the ...