Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this-

mutation signUp($avatar: Upload!) {
  signUp(
    avatar: $avatar
    input: { 
      name: "Siam Ahnaf"
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff8c969e929e97919e99cec6c7bf9e9093d19c9092">[email protected]</a>"
      password: "12345678" }
  ) {
    message
    token
  }
}

To execute this, I sent a request from my Next.js application like this-

var formData = new FormData();
    formData.append('operations', '{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: "Siam Ahnaf", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a79636b676b62646b6c3b33324a736b62656524696567">[email protected]</a>", password: "siam1980"}){message, token}}", "variables": { "file": null } }');
    formData.append('map', '{ "0": ["variables.file"] }');
    formData.append('0', Image);
    await axios({
        url: "http://localhost:3001/graphql",
        method: "post",
        data: formData,
        Headers: {
            'Accept': 'application/json'
        }
    })
        .then(response => console.log(response))
        .catch(error => console.log(error));

However, I am now facing an error stating - Invalid JSON in the ‘operations’ multipart field

I am uncertain of where the issue lies within the 'operations' JSON. Any assistance would be greatly appreciated.

Thank you in advance.

Answer №1

Sharing my response here from a similar question in case that post is closed:

When dealing with quotes within quotes and using JSON.parse, it's crucial to escape them, as others have mentioned. However, simply single escaping the quotes may not be sufficient. Depending on the context, you may need to double- or even triple-escape them.

Here's why:

'{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: \"Siam Ahnaf\", email: \"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34475d5559555c5a5552050d0c74e055b59">[email protected]</a>\", password: \"siam1980\"}){message, token}}", "variables": { "file": null } }'

JavaScript interprets this by recognizing the unnecessary escape attempt of \" within single quotes and converts it into ". Consequently, the parser identifies the value inside the quotes (already escaped):

{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: "Siam Ahnaf", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2c363e323e37313e396e66671f263e373030713c3032">[email protected]</a>", password: "siam1980"}){message, token}}", "variables": { "file": null } }

The syntax highlighter changes colors midway through due to the pre-escaped quotes.

To achieve the desired output, ensure that the initial string processing results in backslashes, necessitating further escaping of THE BACKSLASHES:

'{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: \\"Siam Ahnaf\\", email: \\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02716b636f636a6c6364333b3a427b636a6d6d2c616d6f">[email protected]</a>\\", password: \\"siam198\\"}){message, token}}", "variables: { "file": null } }'

The question arises whether two or three backslashes are required. When the outer string uses single quotes, only double-escaping is needed for each quote maintained. For an outer double-quote string, consider triple escaping to avoid issues with quote preservation.

Remember: Triple escape if attempting to escape the same type of quote used in your string; double escape when dealing with a different type.

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

What is the proper method for effectively employing destructuring?

I'm trying to figure out how to properly return state with a fetched array using the spread operator. Here is my reducer code snippet: function themes(state = [], actions){ switch(actions.type){ case FETCH_THEMES_SUCCESSFULLY: const { th ...

verify whether the image source has been altered

There is an img tag displaying the user's avatar. When they click a button to edit the image and choose a new one, the src attribute of the img changes to the new image src. How can I detect when the src changes? Below is the code for the button tha ...

Strange Node.js Issue

I don't have much experience with node.js, but I had to use it for launching on Heroku. Everything was going smoothly until a few days ago when suddenly these errors started appearing. Error: /app/index.jade:9 7| meta(name='viewport', co ...

Encountered a failure while loading modules in AngularJS

When I tried opening the index.html page using Chrome, I encountered an error stating that the correct modules could not be found. Uncaught SyntaxError: Unexpected token < angular.js:1 Uncaught SyntaxError: Unexpected token < controller.js:1 ...

Your search parameter is not formatted correctly

I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example: http://localhost:3000/patient?filter=name:jack I have implemented a method to retrieve and convert these ...

Dropzone failing to verify the maximum file limit

I am currently using dropzone to upload files on my website. I have limited the number of files that can be uploaded to a maximum of six. The code works perfectly when uploading one image at a time, but if I select more than six images by holding down the ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Creating a new object through manipulation of existing objects

In my attempt to transform an existing object into a new object structure, I am facing some challenges. Here is the current data set: const jsonStructure = { "a11/a22/animations": "snimations", "a11/a22/colours": "sl/colours", "a11/a22/fonts" ...

Can someone guide me on how to make an array filled with dates using Javascript?

I am working on developing a Javascript code that can identify all the days leading up to the current date. Here is what I have managed so far: var titleArray = [ "title1", "title2", ]; var pictureArray = today.toString(); var thumbArray = today.toString ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...

What is the purpose of using a single pipe character within a Vue.js template handlebar expression?

Here is a sample code snippet: <div> {{ name | capitalize }} </div> I have searched through the documentation for vuejs and handlebars, but couldn't find any relevant information. ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Transfer attributes, but have exclusions in React

At times, we all have a common practice of wrapping DOM elements in custom components. <CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth /> In this example, the custom component wraps a button with pr ...

Struggling to retrieve user input from a textfield using React framework

I'm having trouble retrieving input from a text-field in react and I can't figure out why. I've tried several solutions but none of them seem to be working. I even attempted to follow the instructions on https://reactjs.org/docs/refs-and-th ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Locate an array within a Multidimensional array and relocate it to the starting position

I've been attempting to figure out a solution for moving a specific array within another array to the beginning. The problem I'm encountering is that the code I was using, as suggested in a previous question, only removes the last value and plac ...

Is there a way to broadcast a message to all the Discord servers where my bot is currently active using v14 of discord.js?

Can someone assist me in creating code that allows me to send a message to all servers at my discretion? I have not found any resources on this topic for discord.py or the newer versions of discord.js ...