Error occurs during server to server mutation with Apollo Client (query successful)

Currently, I am using apollo-client on my web server to interact with my graphql server (which is also apollo). While I have successfully implemented a query that retrieves data correctly, I encounter new ApolloError messages when attempting a mutation. Oddly enough, when I directly paste the same mutation into GraphiQL, it works flawlessly.

I have ensured that CORS is enabled and functioning properly on my graphql server. As mentioned earlier, copying and pasting the mutation from my code editor into the GraphiQL editor yields successful results.

If anyone could provide insight into this issue or direct me on how to access more detailed information on my graphql-server regarding why I'm receiving a 400 error, it would be greatly appreciated.

Below is the Apollo error output:

{
  "graphQLErrors": [],
  "networkError": {
    "response": {
      "url": "http://localhost:9000/api/private",
      "status": 400,
      "statusText": "Bad Request",
      ...
    }
  },
  "message": "Network error: Network request failed with status 400 - \"Bad Request\""
}
Error
    at new ApolloError (/Users/rkstar/dev/projects/crate/microservices/dashboard/node_modules/apollo-client/apollo.umd.js:1490:23)
    at /Users/rkstar/dev/projects/crate/microservices/dashboard/node_modules/apollo-client/apollo.umd.js:2149:24
    at process._tickCallback (internal/process/next_tick.js:103:7)

**** UPDATE **** I have added middleware before my apolloMiddleware to log the req.headers and req.body information:

req.headers -------
{
  "accept": "*/*",
  "content-type": "application/json",
  "authorization": "JWT ",
  ...
}

req.body -------
{
  "query": "mutation updateTwitterAccessToken($data: TokenInput!) {\n  updateTwitterToken(data: $data) {...\n}\n}",
  "variables": {
    "data": {
      "accessToken": "...",
      ... 
    }
  },
  "operationName": "updateTwitterAccessToken"
}

When calling client.mutate({ ... }) from my web server, I notice that in the req.body, the property is set as:

req.body -------
{
  "query": "mutation ..."
....
}

The confusion lies in why it shows "query": "mutation ..." instead of "mutation": "mutation ...". Any insights on this discrepancy?

Answer №1

Summary

The issue was resolved by correcting the nesting of the return property in my update-token.graphql file.


Finally fixed the problem after realizing a mistake in my graphql mutation. I was attempting to access a field that didn't exist within another field.

I had initially tested my query in graphiql and it worked fine. However, I overlooked the fact that I had un-nested one of my return variables, causing the error. Although I thought I had updated the changes back to the original .graphql file, it turned out I missed that step.

An interesting discovery during this process:

I attempted to use middleware to log my request details ------

router.all('/private',
  bodyParser.json(),
  (req, res, next)=>{
    console.log(JSON.stringify(req.route, null, 2))
    next()
  },
  apolloMiddleware
)

This approach provided useful information, but comparing the requests from graphiql and apollo-client did not immediately reveal the error due to the query format differences.

Eventually, I utilized formatError to display the specific error message:

const apolloMiddleware: any = graphqlExpress(request => ({
  debug: debugMode,
  schema: executableSchema,
  context: request,
  formatError: e =>{
    console.log(JSON.stringify(e, null, 2))
  }
}))

It highlighted the following error:

{
  "message": "Cannot query field \"token\" on type \"UserServices\".",
  "locations": [
    {
      "line": 9,
      "column": 7
    }
  ]
}

Upon reviewing this message, I quickly updated the .graphql file, resulting in a successful execution of the mutation through apollo-client.

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

Is jquery.validate showing errors more than once?

For my testing program, I utilize the jquery.validate plugin to validate user input fields. Here is how it's set up: <script src="js/jquery-1.12.4.min.js"></script> <script src="js/jquery-form-3.51.min.js"></script> <script ...

Preventing Double Click Events on jQuery Spinner

I have been working on an option picker, but now there is a new requirement to make the options configurable. While this shouldn't be too difficult, I am facing some issues with the option picker: Currently, when an item is double-clicked, it will ge ...

Incorrect Request Method for WCF json POST Request Leads to 405 Error (Method Not Allowed)

Hey there, I'm facing an issue with using Microsoft Visual Studio to create a WCF web service. Everything runs smoothly within Visual Studio, but when I try to connect to the service from outside, it fails to establish a connection. At first, I encoun ...

Issue with Mongoose: The function within the .find method is not returning the expected result

How can I successfully pass the result of a function into the .find method? I am trying to use the argument passed via body-parser as the value for the key 'name' if the user submits a non-empty string. If the user submits an empty string, then a ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

Can someone guide me on how to use contract.on() in ethers.js to listen to events from a smart contract in a node.js application?

I've been working on a node.js application using ethers.js to listen to events emitted from the USDT contract Transfer function. However, when I run the script, it exits quickly without displaying the event logs as expected. I'm unsure of what st ...

Experiencing FCM error: Is your data object null?

Currently, I am in the process of sending a push notification through Firebase cloud messaging by utilizing the Firebase admin SDK with nodejs. However, upon attempting to send the push message, an error is occurring: { code: 'messaging/invalid-p ...

Add the useState hook from React to an array

Hey there, I need some help with my code. I am trying to add an element to my array, but it's not working as expected. Can you take a look at what I have written below? const [datesState, setDisabledData] = useState([ format(new Date(2021, 4, 1) ...

Retrieve information according to the object ID with AngularJS UI-Router and $stateParams

I have a unique application that directs to a custom URL based on a specific employee ID parameter when an individual employee is clicked in a list. Upon clicking the employee, users are redirected to a detailed employee page with their ID property as a pa ...

discord.js: Imported array not displaying expected values

I've been facing an issue with accessing elements from an imported array. Even though the array is successfully imported, attempting to access its elements using [0] results in undefined. Here's how I exported the array in standList.js: exports. ...

Is there a way to set up custom rules in eslint and prettier to specifically exclude the usage of 'of =>' and 'returns =>' in the decorators of a resolver? Let's find out how to implement this

Overview I am currently working with NestJS and @nestjs/graphql, using default eslint and prettier settings. However, I encountered some issues when creating a graphql resolver. Challenge Prettier is showing the following error: Replace returns with (r ...

Learn the process of utilizing signed URLs in conjunction with ReactJS to securely store files in AWS

I am currently working on a form where I need to attach images along with regular text inputs in order to submit data to my MongoDB. Here is the code for my post creation function: const [postData, setPostData] = useState({ text: '', i ...

Ways to eliminate the lower boundary of Input text

Currently, I am working on a project using Angular2 with Materialize. I have customized the style for the text input, but I am facing an issue where I can't remove the bottom line when the user selects the input field. You can view the red line in t ...

Is there a way to retrieve the central anchor point position (x, y) of the user's selection in relation to the document or window?

Is there a way to retrieve the center anchor point position (x, y) of the user's selection relative to the document or window? I have tried using window.getSelection() to get selected nodes, but I am unsure how to obtain their position: See an examp ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Empty Ajax array sent to PHP

I am encountering an issue with my ajax form where the values in an array are coming out as null in my PHP response. I suspect that there may be a mistake in my .ajax call. Can anyone provide suggestions or insights on how to resolve this issue? My code sn ...

Steps to temporarily turn off Backbone.sync for a fresh model and then reactivate it once the user clicks the save button

I am currently working with a Backbone collection model that consists of sub-models as elements, along with views to edit it. My objective is to have the syncing functionality "turned off" initially when the model is created, so that the back end is not c ...

Insert metadata tag into the head element of the parent iframe

I am looking to insert a meta tag element into the head element of an Iframe parent. I attempted window.parent.$('head').append('sometext'); This method worked when the source file and iframe file were in the same folder, however it d ...

Personalized jQuery Slider, Go back to initial slide

Working on enhancing my jQuery skills by constructing a basic slider with 3 slides. The slider wrapper, with a fixed width of 1400px and a height of 350px serves as the outer container. Within this wrapper lies an unordered list where its items are floate ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...