Troubleshooting the issue: "Error - 'Missing \"data\" payload in the request' when using Vue.js with Strapi"

When attempting to create a new entry in strapi by sending a post request in vue.js, I encountered the following error:

message: 
    Missing "data" payload in the request
    

P.S: I also need to be able to upload files. I have read that using formData is necessary for this, but I am unsure how to go about doing that.

Here is the code snippet:

<script setup>
    import { ref } from 'vue';

    // Define refs for form fields
    const fullName = ref('');
    const emailAddress = ref('');
    const phoneNumber = ref('');
    const uploadPhoto = ref(null);
    const location = ref('');
    const merchantId = ref('');
    const acuityLink = ref('');
    const acuityId = ref('');
    const acuityKey = ref('');

    // Function to handle file input change
    const handleFileChange = (event) => {
      uploadPhoto.value = event.target.files[0];
    };

    const submitForm = () => {
        // Create a FormData object to send the form data
    //   const formData = new FormData();
    //   formData.append('fullName', fullName.value);
    //   formData.append('emailAddress', emailAddress.value);
    //   formData.append('phoneNumber', phoneNumber.value);
    //   formData.append('uploadPhoto', uploadPhoto.value);
    //   formData.append('location', location.value);
    //   formData.append('merchantId', merchantId.value);
    //   formData.append('actuityLink', actuityLink.value);
    //   formData.append('acuityId', acuityId.value);
    //   formData.append('acuityKey', acuityKey.value);
    //   console.log(fullName.value, uploadPhoto.value)
    const strapi = {
            StoreName: fullName.value,
            StoreLocation: location.value,
            merchant_id: merchantId.value,
            ActuityLink: acuityLink.value,
            PhoneNumber: phoneNumber.value,
            ActuityKey: acuityKey.value,
            ActuityID: acuityId.value
    }

      fetch('http://localhost:1337/api/barbers-stores', {
        method: 'POST',
        header: {
            Authorization: 'Bearer ...',
            "Content-Type": 'application/json'
        },
        body: JSON.stringify({data: strapi})
      })
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(error => console.log(error))
    };

    </script>

    <template>
      <section class="container">
        <header>Registration Form</header>
        <form action="#" class="form">
          <div class="input-box">
            <label>Full Name</label>
            <input type="text" placeholder="Enter full name" v-model="fullName" required />
          </div>
          <div class="input-box">
            <label>Email Address</label>
            <input type="text" placeholder="Enter email address" v-model="emailAddress" required />
          </div>
          <div class="input-box">
            <label>Phone Number</label>
            <input type="number" placeholder="Enter phone number" v-model="phoneNumber" required />
          </div>
          <!-- New Fields -->
          <div class="input-box">
            <label>Upload Photo</label>
            <input type="file" accept="image/*" @change="handleFileChange" required />
          </div>
          <div class="input-box">
            <label>Location</label>
            <input type="text" placeholder="Enter location" v-model="location" required />
          </div>
          <div class="input-box">
            <label>Merchant ID</label>
            <input type="text" placeholder="Enter Merchant ID" v-model="merchantId" required />
          </div>
          <div class="input-box">
            <label>Acuity Username</label>
            <input type="text" placeholder="Enter Acuity Username" v-model="actuityLink" required />
          </div>
          <div class="input-box">
            <label>Acuity ID</label>
            <input type="text" placeholder="Enter Acuity ID" v-model="actuityId" required />
          </div>
          <div class="input-box">
            <label>Acuity Key</label>
            <input type="text" placeholder="Enter Acuity Key" v-model="actuityId" required />
          </div>
          <!-- End of New Fields -->
          <button @click.prevent="submitForm">Submit</button>
        </form>
      </section>
    </template>

Answer №1

It seems like you encountered an error while using new FormData. While I don't use view, here's an example in remix where I send both an image and data together.

export async function recommend(data, image) {

  const baseUrl = process.env.BASE_URL
  const query = `/api/recommendations`;

  const url = baseUrl + query;

  const hasImage = image._name === "" ? false : true;

  const formData = new FormData();
  formData.append('data', JSON.stringify(data));
  if (hasImage) formData.append('files.image', image, image.name);
  const response = await fetch(url, {
    method: 'POST',
    body: formData,
  })

  return response.json();
}

Take note of how I am appending my strapi data - by passing the entire object to 'data' instead of individually as you were doing.

  formData.append('data', JSON.stringify(data));

I hope this explanation proves useful for you.

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

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

Switch up the text within the URL of the background image

Simply put, this is the structure I have: <div id="RelatedPosts1"> <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div> <div class="related-posts-thumb" style="background: url(http: ...

The submit form and cordova functions are failing to trigger

I am encountering an issue where I cannot successfully call the submitForm() function when attempting to trigger it via ng-submit. The function does not execute as expected. How can I troubleshoot and resolve this problem? (function () { 'use str ...

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

Is it possible to utilize the AmMap API for developing an Android application?

I am currently in the process of creating a unique application with HTML, JS, and jQuery Mobile that will feature interactive maps. I have been searching the web for APIs to incorporate interactive maps into my project without using Google Maps APIs when I ...

Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format? For example, how can we convert the array ["a.b.c.d", "a.c.e.f", "a.b.c.g"] into the following JSON structure: items:{ text: "a", items:[ { ...

Authenticate through Twitter when using PhoneGap Cordova

Looking to implement Twitter login in my application using JavaScript and HTML. How can I redirect users to the Twitter login page when they click on the "Sign In with Twitter" button? ...

function for app.get callback in express.js

Hey there, I'm a bit puzzled by the syntax of the get route function because there seem to be two versions. Here's an example of some code: First one: app.get('/users', function(req,res){ ... }); Second one: app.get('u ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

Adjusting the height of the Sencha Touch container to accommodate its content

In Sencha Touch, I have a view that generates a popup box from the right when a button in the bottom toolbar is clicked: Ext.define('TheApp.view.PopupTablet',{ extend: 'Ext.form.Panel', xtype: 'popupbox', confi ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

Using webpack to access a bundled React class in an HTML file

Is there a way to access pre-built components directly within the HTML file that links to the build? I've been attempting the following - Inside bundle.js var React = require('react'); var ReactDOM = require('react-dom'); ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

Using plain JavaScript, adding an element to an array by pushing the value of a string variable in an index position rather than pushing the

I have the following JavaScript code snippet: let array = []; const datas = [ 'name1', 'name2', 'name3', ]; async function getData() { datas.forEach((data) => { let myData = data.name; if(!array.include ...

Can uniform columns be created in separate HTML elements?

Looking to create a uniform list in HTML, where the columns inside each panel line up perfectly. See the desired layout: In this example, Col_1 has a width of "BBBBB", as it is the widest content in that column, while Col_2 has a width of " ...

Quasar: Drawer now switches to Mini-mode automatically

Currently, I am using Quasar and I want the drawer to automatically switch to mini mode when users resize their browser window to make it smaller. At the moment, the drawer always remains open even when I narrow the browser width. Below is what I have tri ...

JavaScript Bridge function in WebView not invoked

I encountered a strange issue with my application, which functions as an e-reader. To invoke functions for the web view, I utilize a JavaScript class: public class MyJavaScriptInterface { Context mContext; /* Instantiate the interface ...

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...