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

What is the process of TypeScript module resolution within the Play framework?

In my Play project, I am interested in incorporating Angular 2 with TypeScript. Utilizing the sbt-typescript plugin and the angular2 WebJAR, I have encountered a situation where Play places the extracted WebJAR in target/web/public/main/lib/angular2. Ideal ...

Building a Vue application with Node.js, Express, and XAMPP requires careful consideration of the project

I'm looking to develop a CRUD application using technologies such as: - Vue.js - Node & Express - mysqli (xampp) What would be the most effective approach to structuring the project's directory and files tree? Is it preferable to separate into t ...

The `forEach` method cannot be called on an undefined node.js

I have been developing a small study website but encountered an issue with the title. Despite extensive internet research, I have not been able to find a solution. The system I am using is Ubuntu with node.js, express, and mysql. app.js var fs = requir ...

Direction of the grid in Tailwind CSS

Here is the grid, displayed like this: 1,2,3 4,5,6 7,8,9 I am looking to adjust the grid within the parent Div to display like this: 1,4,7 2,5,8 3,6,9 (please note that there could be more elements than just 9) <div className="grid h-full grid-co ...

Difficulty in establishing a handshake within an ExpressJS Node application due to Let's Encrypt SSL certificate issues

I'm currently facing an issue while configuring a node server with Let's Encrypt certificates. I am utilizing Express to create an HTTPS server as shown below: var fs = require('fs'); var app = require('express')(); var https ...

Navigating and exploring data stored in a mongoose database

Currently, I am attempting to filter data based on a specific id (bWYqm6-Oo) and dates between 2019-09-19 and 2019-09-22. The desired result should return the first three items from the database. However, my current query is returning an empty array. I wou ...

Navigating Passport.js: uncovering ways to reach the user object post-authentication

Currently implementing Passport.js for user login using username and password, following the sample code from the Passport site. Here are the essential parts of the code I have so far: app.use(passport.initialize()); app.use(passport.session()); passport ...

Is it possible for a Node.js/Express server to securely handle all UTF-8 characters?

At the moment, my setup involves a node server running Express that is connected to a PostgreSQL database with UTF-8 encoding support. In terms of frontend, I'm using Angular which has built-in measures for preventing unsafe injection. I am curious i ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

NextJS custom credit card form with recurring payments using Paypal

I have successfully implemented subscriptions in nodeJS with the following code: const createSubscription = async () => { const accessToken = await getAccessToken(); const response = await axios.post( `${PAYPAL_API}/v1/billing/subscriptions`, ...

Retrieving the Object value in Primeng p-dropdown when there is a change in selection

In my p-dropdown, I am trying to extract the selected value. <p-dropdown optionLabel="name" [options]="things" placeholder="Select Thing" [(ngModel)]="input" (onChange)="getValue(input)"></p-dropdown> typescript: //each lin ...

Navigating from Node.js to different directories within the views folder

I am utilizing Express to create a basic CRUD system. I have separate views/posts and views/users for each controller, which I want to organize accordingly. In my app.js file, I use app.set("views", path.join(__dirname, "./views/posts")); to register the ...

Define security JWT token in the TypeScript REST API using the swagger annotations

Utilizing typescript-rest and incorporating swagger, a package known as typescript-rest-swagger has been integrated. Efforts to include the Bearer token into swagger have proven unsuccessful thus far. Removing the authorization middleware seems to allow ...

The error message indicated that a Promise<string> was expected, but instead a Promise<string|number> was received

Confusion Over Promise Type Error How did the TypeScript compiler generate the error message displaying Type Promise <string|number> ... in the following scenario? Type 'Promise<string | number>' is not assignable to type 'Prom ...

Encountering the error message "OAUTH_CALLBACK_ERROR invalid_client" while trying to authenticate with a custom provider through Next

I am experimenting with NextAuth to authenticate using a custom oauth2 provider (Whoop). However, after the login process is completed on the Whoop servers and I'm redirected back to my application, NextAuth throws the following error: [next-auth][err ...

Upon successfully logging in with basic authentication, Nginx issues a 404 error code

After deploying my website built with next.js on my test server, everything was working fine. To protect the admin area (/admin url), I set up nginx basic auth using the following steps: Installed apache2-utils by running sudo apt-get install apache2-uti ...

The functionality of Next.js dynamic routes is compromised once deployed

I recently completed a website using Next.js with the following folder structure: pages |- [path] | |- index.js | |- [for-students] | |- [path] | | |- index.js | | index.js | events.js During development, everything functioned smoothly. I utilized ...

Employing multer in conjunction with superagent to enable file uploads from a React application

I am new to using multer and experiencing some difficulties with it. My goal is to upload an image file from a react client using the superagent library to my server. However, the req.file data always shows as undefined in my code: On the server side : ...

Transferring form data from Jade to Node.js for submission

My Jade template includes the following form structure: form(action='/scheduler/save/' + project.Id, method='post') div.form-group label.control-label.col-md-2 RecurringPattern di ...

The requirement of the second parameter being optional or required will depend on the value of the first

Is there a way to make the second parameter of my function optional or required based on the value of the first parameter? Here's an example code snippet: enum Endpoint { USERS = '/users/:userId', ORDERS = '/orders' } typ ...