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

Opting for CSS3 transitions over jQuery animate

Currently, I am working on animating a block of HTML that involves fading in (opacity) and slightly moving from the left (margin-left)... $('.latest-stats').delay(1000).animate({ opacity: 1, marginLeft: '55px' }, 1000, function () { ...

Managing the placement of the expanded autocomplete input in Material-UI

Whenever I use the autocomplete fields on my website, I've observed an interesting behavior. When I select multiple options, the height of the input increases significantly, causing everything below it to shift downward like this. Is there a way to m ...

Delivering a protected, locally hosted NextJS project with numerous subdomains

In the configuration of NextJS' server.js, you can ensure secure self-hosted server by including: https.createServer({ key: fs.readFileSync('./privkey.pem'), cert: fs.readFileSync('./cert.pem'), ca: fs.readFileSync('./ch ...

Setting a default image for the img tag in case the src is invalid in React is a common problem that many

Is there a way to set a default image for an img tag if the src link is not valid in React? I attempted to use onerror, but it doesn't seem to be effective. This issue arises in Next.js with hooks implementation. <img alt="Site Logo" sr ...

Tips for stopping variables from leaking in JavaScript

I'm currently working on a JavaScript code for my task manager website. Each page has its own JS file, but I've noticed that the data saved in one file seems to leak over to the others. How can I contain these variables so that tasks don't s ...

Triggering jQuery Submit Form when Form is Modified

I need help with automatically submitting a form using jQuery when an input changes. The specific input I am working with is a date picker, and I want the form to be submitted as soon as a user makes a selection. <form id="select_date" name="select_da ...

Showcasing an HTML table using Material-UI

Currently, I have a list of issues being displayed in my browser using the material-ui code below: <Paper className={classes.root} elevation={4}> <Typography type="title" className={classes.title}> All Issues </Typography> ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

What is the best way to handle parsing JSON using external middleware after the removal of body parser in Express?

Having trouble parsing JSON with external middleware after Express removed the body parser? I used to rely on Express bodyParser for handling JSON posts, but after updating Express, my JSON requests are returning null. It seems like I was using the wrong ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

What could be causing the asynchronous function to return a pending promise even after using the await keyword?

I seem to be overlooking something as I cannot comprehend why my promise does not resolve. I have simplified the code to this basic example: ... console.log("before"); const promise = second(); console.log("after"); console.l ...

Toggle the visibility of a component by clicking on a specific title within a table, dependent on the column title in Angular 9

Currently, I am developing an Angular application focused on creating a COVID-19 tracking app. In this project, I have designed 2 components - Component A displays a list of all states, while Component B lists all districts within a particular state. To ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

Utilize Boolean operators such as AND, OR, and NOT to locate specific keywords within a text, mirroring the search capabilities

Is it possible to perform Google-style searches in strings using operators like "or", "and" and "not" with regular expressions? For instance, I aim to search for the words "Javascript", "PHP" and "Perl" within a given string in these ways: Javascript an ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

Implementing dynamic attribute id addition to select option

Here's the code snippet I'm currently working with: Included HTML <select id="drop_opts"> <option>1<option> <option>2<option> <option>3<option> </select> ...

My initial junior UI/UX assignment: Can you confirm whether this form modal dialog is pixel-perfect, and offer any suggestions for improvements

Currently diving into my first project as a Junior UX/UI Designer. Coming from a background in software engineering, I decided to challenge myself by focusing on design. I'm seeking feedback on the pixel perfection of this modal window, which my seni ...

What is the best way to develop a parent component tailored for individual pages in order to integrate react context within it?

I need to use a specific react context for certain pages in my project. Instead of creating the context in the root file app.js, I want to create it only for these specific pages. Is there a way to create a parent component (wrapper) that can be placed ar ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...