How can I resolve the problem of transferring retrieved data to a POST form?

When it comes to the form, its purpose is to send data fetched from another API along with an additional note. The fetched data was successfully received, as I confirmed by logging it to the console. It seems that the form is able to send both the fetched data and the note to the backend correctly, as evidenced by logging req.body to the console. However, the problem I'm encountering is that the response I receive is a 400 error. Interestingly, when I manually test this process using Postman to send the data and note to the form POST API, it works perfectly fine and saves to the database without any issues. The same cannot be said for the app.

Answer №1

Multer is designed to process "multipart/form-data" requests, however, the content type you are transmitting is "application/json".

Answer №2

Upon making the necessary changes to the body type, I encountered a 400 error.

import Cookies from "js-cookie";

export default async function submitFormDataWithVehicleDetails(formData: FormData) {
  const url = "http://127.0.0.1:3000/api/v1/hire";

  const token = Cookies.get("token");

  const response = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
    },
    body: formData,
  });

  if (!response.ok) {
    const errorResponse = await response.json();
    throw new Error(
      `Failed request with status ${response.status}, ${JSON.stringify(
        errorResponse
      )}`
    );
  }

  const data = await response.json();
  return data;
}
"use client";
import { useState } from "react";
import submitFormDataWithVehicleDetails from "@/lib/postHire";

export default function Form({ vehicle }: { vehicle: Vehicle }) {
  const {
    name,
    seat,
    price,
    description,
    type,
    pictures,
    colour,
    transmission,
  } = vehicle;
  const [note, setNote] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const vehicleDetails: FormDetails = {
      name: name,
      pictures: pictures,
      description: description,
      colour: colour,
      transmission: transmission,
      type: type,
      seat: seat,
      price: price,
    };

    const formData = new FormData();
    formData.append("note", note);
    Object.entries(vehicleDetails).forEach(([key, value]) => {
      if (Array.isArray(value)) {
        value.forEach((item, index) => {
          formData.append(`${key}[${index}]`, item);
        });
      } else {
        formData.append(key, typeof value === "number" ? String(value) : value);
      }
    });

    try {
      await submitFormDataWithVehicleDetails(formData);
      console.log("Submission Successful");
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <div className="mb-3">
        <label htmlFor="examplenote1" className="form-label">
          Include Note
        </label>
        <input
          type="text"
          className="form-control"
          id="exampleInputEmail1"
          aria-describedby="textHelp"
          placeholder="Don't forget snacks"
          value={note}
          onChange={(e) => {
            setNote(e.target.value);
          }}
        />
      </div>

      <button type="submit" className="btn btn-primary">
        Submit
      </button>
    </form>
  );
}

No other modifications have been made.

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

Guide on Adding a Map to a List in JavaScript

Currently, I am trying to extract data from a form and add it as a map to my list. However, an error message is displayed: Cannot read property 'url' of undefined express = require("express"); app = express(); var bodyParser = require("body- ...

Elevating the Efficiency of Express Routing

I currently have multiple express routes that perform similar functions, except for the .put route which handles specific functionality. I am seeking advice on how to best refactor this code. Required Modules var Ale = require('../models/ale ...

When attempting to create a JavaScript class within a NextJS library that utilizes server-side code, an error is encountered on the frontend despite not

Currently, I am in the process of developing a NextJS project and working on constructing a library that can be utilized in future projects. As part of this library, I have created a JavaScript class detailed below: export class EmailManager { private ...

Pug and ExpressJS combo failing to implement Tailwind styles

In my project using Express/Node and Pug for views, I've been struggling to incorporate Tailwind CSS for styling. Despite adding the necessary classnames in my Pug files, the styles don't seem to be applying correctly. Has anyone faced a similar ...

The front-end is receiving a CORS error from the API, despite the fact that it should be configured to

I am currently working on an API using FastAPI, and the frontend is built with next.js. However, I am facing an issue where the next.js application is unable to successfully make a post request to the API due to CORS errors. Despite setting the CORS config ...

What is the best method for transferring information in TwitterStrategy using PassportJS?

I am managing three different types of users: Viewer (click here to sign in: auth/v/twitter) Creator (click here to sign in: auth/c/twitter) Admin (click here to sign in: auth/a/twitter) In addition, I have 3 different database collections: c_view ...

Error: The post method in $setup is not defined in Vue Composition API

Dealing with a frustrating issue in my Vue application. One page is functioning perfectly fine, while the other is causing trouble by displaying this error: The first page loads a collection of wordpress posts (Blog.vue) without any issues, but the second ...

Showcasing solely the latest entry in the database utilizing nodeJS

I am having an issue with my code where it is only displaying the last record from the database. How can I modify it to display all the records from the database using nodeJS? Any assistance would be greatly appreciated. Thank you. var express = require ...

Using NodeJS to embed documents with Mongoose

Currently, I am honing my skills in Mongoose and Node JS. My aim is to integrate the Comment schema within the Article schema. However, when I try to run the server, it throws an error message like this: An error stating "Invalid value for schema Array ...

What is the process of serving an mp3 file in Node.js?

Currently, I am in the process of creating a basic web application where pressing a button triggers a sound (an mp3 file stored on the server). //html file <script> function playSound () { document.getElementById('play').play(); } ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

Angular HttpInterceptor failing to trigger with nested Observables

Utilizing a HttpInterceptor is essential for adding my Bearer token to all calls made to my WebApi. The interceptor seamlessly functions with all basic service calls. However, there is one specific instance where I must invoke 2 methods and utilize the re ...

What is the best way to transmit a response using JSON instead of Jade?

//This is the code in my index.js file var express = require('express'); var router = express.Router(); /* Display the home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Movie Datab ...

Solving the Cache Busting Problem in ReactJS and Express

Is there a way to prevent cache busting by incorporating version numbers in the index.html file name (like index.hash.html) generated with html-webpack-plugin? I'm facing the issue where the browser continues to retrieve the old cached index.html file ...

Leveraging ZOD's discriminatedUnion() method to differentiate among three different forms

ValidationSchema = z.object({ AuthenticationBlock: z.object({ ChoiceOfForm: z.enum() DataBlock: z.discriminatedUnion(ChoiceOfForm, [ z.object({ ChoiceOfForm = 1, empty fields}) //corresponds to the basic form z.object({ ChoiceOfForm = 2, just ...

Exploring Variable Scope in EJS/Express

I've been exploring variable scope and came across this simple code snippet: const params = { versions: versions, user: user, statsParams: statsParams, csrfToken: csurf.createToken(req), }; res.render("server/edit& ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Ways to structure this updateone query for mongoose formatting

UPDATE: After making adjustments to the query using arrayFilters recommended by someone here, the query is returning success. However, the values in the database are not being updated. I am attempting to update specific fields within a MongoDB collection ...

How to retrieve and send the current URL path to a Helper using Node.js and Handlebars

I am currently working on developing a meta tag handlebars helper that extracts the URL pathname and uses it as a reference in a switch statement to determine the appropriate string for my HTML head meta tag. However, I am facing difficulties in finding th ...

NextJS's conversion of HTML to image is malfunctioning, resulting in the download of the identical reference

Having encountered difficulties with the html-to-image library while working on a Next.js project, I used the following code to convert images: import Image from "next/image"; import {toPng} from 'html-to-image' const divReferenceA = u ...