Is there a way to successfully transmit data from a Vue 3 form to a Laravel server?

I am attempting to send data along with a file to the server

Currently, I have implemented the following code on vue 3:

const formData = new FormData();
  formData.append('responsible_name', groupForm.value.responsibleName);
  formData.append('responsible_phone', groupForm.value.responsiblePhone);
  formData.append('responsible_email', groupForm.value.responsibleEmail);
  formData.append('appeal_type_id', groupForm.value.appealTypeId);
  formData.append('municipality_id', groupForm.value.municipalityId);
  formData.append('educational_institution_id', groupForm.value.educationalInstitutionId);
  formData.append('users', groupForm.value.users);
  formData.append('flows', groupForm.value.flows.filter((flow: EventFlow) => flow.select).map((flow: EventFlow) => flow.id));
  formData.append('appeal_doc', fileInput.value.files[0]);

Here is the code for sending the data:

const headers = {
  'Content-Type': 'multipart/form-data',
  Accept: 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Cache-Control': 'no-cache',
};
const makeAppeal = async <T>(body: BodyFetchData): Promise<T> => {
    try {
      const data = await fetchData('/appeal/create', 'POST', body, headers);
      return data as T;
    } catch (e) {
      return Promise.reject(e);
    }
  };

The response from the server indicates a 422 error with the following messages:

{"message":"The flows field is required. (and 4 more errors)","errors":{"flows":["The flows field is required."],"responsible_name":["The responsible name field is required."],"responsible_phone":["The responsible phone field is required."],"responsible_email":["The responsible email field is required."],"users":["The users field is required."]}}

Below are the headers used for the request: https://i.sstatic.net/H3wegSaO.png

const fetchData = async <T>(url:string, method: MethodFetchData = 'GET', body: BodyFetchData = '', headers: Record<string, string> = {}): Promise<T> => {
  const apiUrl = `${useRuntimeConfig().public.domainApi}${url}`;
  const headersDefault = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    'Access-Control-Allow-Origin': '*',
    ...headers,
  };
  try {
    if (method === 'GET') {
      const data = await $fetch(apiUrl, { headers: headersDefault, method, params: body || {} });
      return data as T;
    }
    if (method === 'POST') {
      const data = await $fetch(apiUrl, { headers: headersDefault, method, body });
      return data as T;
    }
    return Promise.reject();
  } catch (error) {
    return Promise.reject(error);
  }
};

I have tried using XHR and various other methods, but I continue to encounter this issue. Interestingly, when testing with Postman, everything works fine, whereas utilizing JavaScript presents these problems.

Answer №1

After struggling with my issue, I finally found the solution. It turns out that I was missing a header with the boundary x, which is generated dynamically for multipart/formdata.

The answer to my problem was discovered by appending an array to FormData and sending via AJAX

In the end, I decided to remove all headers except:

Accept: 'application/json',

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 methods can be used to stop the browser from automatically redirecting to the FORM action following an Ajax submission?

I am facing an issue with uploading multiple files using a Jquery Ajax submit. Although I have added a Return False, after submitting the browser still redirects to the specified URL in the form. Interestingly, if I switch from using FormData to $("#uplo ...

Attempting to increase a variable by 1, only to find that it appears to be doubling on its own

As I work on developing a quiz, I encounter an issue with my code. When I click on the question_holder div, variable x seems to be doubling instead of incrementing as expected. The value of x is supposed to increase by one each time, but it appears to ski ...

Count insensitivities - Javascript

I'm currently using a counter to find occurrences of a substring within a string, but it's case sensitive. Here's my current code: count = (string.match(new RegExp(substring, 'gm')) || []).length; For instance, if the substring a ...

Issues arise when using jQuery's ajax() method with processData set to false, as it still adds form data to the URL, among

Today, I am delving into the world of jQuery to enhance a form's functionality, particularly to interact with a MySQL database. Here is the form I am working with: <form class="loginform" id="loginform" name="loginform"> <input type="ema ...

Using R plotly to show an image when hovering over a location on a map

After successfully implementing the technique of displaying an image on hover in a regular R plotly chart, I encountered issues when trying to apply the same method to a plotly map. Specifically, the approach broke down and failed to display the image. Can ...

Error: A reference to an undefined alertbox with a value extracted from a list was not caught

When I click on a button, I want to display the first value in a list using an alert. I found some inspiration from this discussion. Although the original solution used a table instead of a list, I attempted to adapt it to my needs. However, it seems like ...

a code translator for running compiled programs

I'm curious about executing Windows or GNU/Linux programs directly from a webpage. This is not related to any type of Remote Desktop functionality. My vision involves a user opening a webpage that includes a concealed file containing executable code o ...

Issues regarding innerHTML

I have a collapsed table with a link that collapses its content. My goal is to change the link (such as from "+" to "-" and vice versa) using JavaScript. I was able to achieve this, but now my table no longer collapses. Here is the code snippet: <div c ...

Observing the inner workings of a vuex store

I am currently working with a store in Vue. Here is an example of MyStore.vue: export default { namespaced:true, state: { data: [], } // actions, mutations, etc } I am trying to monitor the store for new data updates. In MyOtherVueFile.vue: ...

Adjusting the width of the container <div> will automatically resize the inner <div> to match

I have a main container element. .wrapper{ border:1px solid blue; position:relative; top:20%; left:30%; height: 300px; width: 350px; } When I adjust the width of the parent container, the child box does not reposition itself accor ...

Guide on retrieving JavaScript variables in a JSON response and showcasing their values on a web page

I need to show the data from a JSON response: item.php $ItemList = array(itemcode=>EATERY, itemname=>'Popcorn') ; $ItemDisplay = " '<div>' + document.write(this.itemname) + ' - ' + ...

Struggling with arrays within arrays

Currently, I am in the process of working on a react project and faced with the task of accessing data within a deeply nested object. Here is an example snippet of the object: {name: "Products", attributes: {…}, children: Array(1), value: "", getElem ...

Trigger the celery task with a single button click

I have developed a django application which includes a celery task responsible for organizing database tables. This particular celery task involves heavy table movements and lookups within over 1 million rows, taking approximately 8 seconds to complete. T ...

Moving a div horizontally while clicking and holding on a control button with a smooth animation effect

I am currently working on a new feature inspired by a previous question I found on Stack Overflow. My goal is to make the scrolling start slowly and then gradually speed up. However, I am facing an issue with using easing in the animate function as it get ...

Score increase in a jQuery based quiz

Currently, I am in the process of developing a jQuery quiz where I have successfully been able to calculate the total value of each answer. However, I am now looking to enhance the quiz by incorporating a function that will update specific variables with p ...

Using JQuery .ajax to store information in the database

I'm in the process of saving 2 different pieces of information into the database using JQuery and the .ajax function. Specifically, I need to save the postID and the userID in a WordPress environment. While I have a good understanding of most of the f ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Refreshing JWT Tokens in Laravel-Vue App

I've implemented the jwtAuth package by Tymon to manage authentication between my Laravel backend and Vue front end SPA. I've created an AuthController based on the documentation with minor modifications to suit my requirements, and everything is ...

Incorporating Anchor Text as the Title in Real-Time

As of now, I have this snippet of HTML code <a href="http://www.google.com">Google Website</a><br /> <a href="http://www.yahoo.com">Yahoo Website</a><br /> <a href="http://www.bing.com">Bing Website</a& ...

Tips for adding an active class when a link is clicked

I am working on a Sidebar component and need to apply the active_class_link style to the DIV element when the onClick() event occurs. Although I have set up the function, I am unsure how to apply this for each DIV within my component. The desired behavior ...