What could be the reason for the transmission of blank fields?

An unusual issue arises when an empty letter is received in the mail, indicating that all dynamic variables are undefined. There are no errors detected on either the server or client side. However, upon checking the console output of rec.body, the expected data does not appear.

The resulting outcome appears as follows:

body: { stream: undefined, source: null, length: null }

The API request function is structured like this:

    const handleSubmitForm = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        
        // Sending data to the server
        const response = await fetch('http://localhost:3000/api/sendMail', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                senderEmail: formInputs.email,
                name: formInputs.name,
                message: formInputs.message,
                floortype: selectedFloor,
                postcode: formInputs.postcode,
                location: formInputs.location,
            }),
        });

        if (response.ok) {
            // Handling successful sending
            console.log('Email successfully sent!');
        } else {
            // Handling sending error
            console.error('Error sending email');
        }
    }

This is how the API code is structured:

import { NextApiRequest } from 'next';
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1765787a767972797c78717b7919666274767c70087d787a">[email protected]</a>',
        pass: '********',
    }
});

interface MailData {
  senderEmail: string;
  name: string;
  message: string;
  floortype: string;
  postcode: string;
  location: string;
}

export async function POST(req: NextApiRequest) {
    try {
      // Parsing the request body as JSON
      const { senderEmail, name, message, floortype, postcode, location }: MailData = req.body;
      console.log(req)

      // Email content
      const mailOptions = {
        from: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a1bcbeb2bdb6bdb8bcb5afbcbca1a093b4beb2babffdb0bcbe">[email protected]</a>',
        to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93e5fce5f2e0f2fda1a3a3a7d3f4fef2faffbdf0fcfe">[email protected]</a>',
        subject: 'New Request from Visitor',
        text: `Name: ${name}\nEmail: ${senderEmail}\nPostal Code: ${postcode}\nCity: ${location}\nDesired Flooring Type: ${floortype}\nQuestion: ${message}`,
      };

      await transporter.sendMail(mailOptions);
      return NextResponse.json({ success: true });
    } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, error: 'Error sending email' });
    }
}

Answer №1

Welcome to the wonderful world of Stack Overflow. Let's dive into the issue at hand:

  1. When working with nextjs, there's no need to manually add headers for fetching data from your site. Nextjs takes care of forwarding some headers automatically.
const response = await fetch('http://localhost:3000/api/sendMail', {
            method: 'POST',
            body: JSON.stringify({
                senderEmail: formInputs.email,
                name: formInputs.name,
                message: formInputs.message,
                floortype: selectedFloor,
                postcode: formInputs.postcode,
                location: formInputs.location,
            }),
        });
  1. If you're not receiving data, it could be because you need to convert it to JSON format first. Give this a try:
const requestData: MailData = await req.json();
      console.log(requestData)

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

Angular and Ionic collaborate by using ngFor to pass on the item.id during a (click) event

I have a list of items and I want to dynamically change the height of a card when I click on a button that is located on the card. Can anyone guide me on how to achieve this? I attempted to pass the item.id through a click event and use the id in a functi ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Include two arguments when making a $http POST request

I am facing a situation where a single property can have multiple images, but each image can only be assigned to that one property (one-to-many relationship with propertyId as foreign key). In the HTML, I am fetching the propertyId and passing it along wi ...

I'm struggling to include a link in my project card component - I've tried using both the Link tag and anchor tag, but so far, I haven't been successful in

I am having trouble getting the link tag to work properly in my UI. I have tried using both the link and anchor tags, but neither seems to be functioning as expected. Can someone please advise on how to fix this issue? https://i.sstatic.net/tAD7C.png I w ...

Breaking down strings using delimiters in JavaScript

Looking for a solution to parse a string with markers: 'This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}' I want to transform it into an array that looks like this: [ {marker: false, value: 'This is&ap ...

Utilize TypeScript in creating a Chrome extension to fetch elements by their ID

I'm currently working on a Chrome extension using Angular and Typescript, and I have encountered an issue with accessing the document element by its id from the active tab. While this works perfectly fine in JavaScript, I am facing difficulties in ach ...

What is the best way to refresh a Component upon sending data to the server?

I'm in the process of developing a cross-platform application. I have a TabView Component that needs to update a tab after sending data to the server. During the initialization (ngOnInit) phase, I dynamically set the content of my tab. However, when I ...

Ways to fix a "define is not defined" issue when utilizing jasmine karma with compiled typescript for component testing

I'm faced with an issue in my typescript app where the compiled code is stored in a single file named myjs.js within the js folder. Additionally, I have karma jasmine configured on my workspace. Inside myjs.js, there's a segment of code like thi ...

How can I create an Onclick function that works for multiple buttons sharing the same ID?

Having an issue with a component that loads data using buttons. I have a function that updates the state/variable based on the button ID, but since all button IDs are the same, it only works for the first button... I'm struggling to assign unique IDs ...

Encountered an error: When trying to install styled-components using npm, there was an issue reading properties of null, specifically 'edgesOut'

C:\Users\user\Desktop\react_sce\test1> npm i styled-components Oops! An error occurred while trying to install styled-components. It seems like there's a problem reading properties of null (specifically 'edgesOut& ...

Develop a higher-order authentication component for securing routes in Next.js

Currently, I am developing the authentication system for my Next.js application. I have set up a /api/auth/login endpoint to handle user login requests. Upon successful validation of user data, I generate an HTTP-only cookie containing a JWT token and send ...

The dark mode feature in my Mac project is essential. I am currently leveraging Next.js alongside React and TypeScript

Struggling to implement dark mode in my Mac project. Utilizing Next.js with React and TypeScript, but can't seem to get it right. I've attempted the following methods without success. Any suggestions? const config: Config = { plugins: [ re ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...

Transform "<Mutation>" to useMutation

In my removeUser page, I have implemented a < Mutation > and handled errors using the submitForm() function. The initial code worked perfectly: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); con ...

Is there a way to incorporate new members into a pre-existing type in TypeScript?

While examining the definition file for the commander project, one can observe the following interface being utilized: interface IExportedCommand extends ICommand { Command: commander.ICommandStatic; Option: commander.IOptionStatic; [key: stri ...

Transforming time into luxon time frames and hours

Is there a way to convert this block of code from moment.js to luxon? Here is the code snippet for reference: The following code is written using moment.js, but I would like to achieve the same functionality using luxon. timezone: null, getIn: moment() ...

displaying a grey box on Google Maps using an *ngIf directive

I am working on a component that displays a map. @Component({ selector: "panda-map", template: ` <div class="map" [style.height.px]="height"> </div> ` }) export class PandaMapComponent implements OnInit { @Input ...

The latest version of Reinforced.Typings, 1.4.0, is causing build crashes when upgrading from the previous version 1

Recently, I updated my C# 4.5.1 .NET library named "ViewModels" to the newest 1.4.0 version of the Reinforced.Typings library/tool using NuGet. This tool allows me to convert my C# code to .ts files. During the upgrade process, I chose not to overwrite th ...

Best practice for incorporating types into a Redux-toolkit reducer

As someone who is relatively new to TypeScript, I have a specific goal in mind. I am looking to create an interface where: interface ActionType { fieldName: {any one key from the interface FormStateType listed below such as 'name', 'age&ap ...

Why does React useRef function smoothly in development but encounter errors in production?

The function "header" is using the React Hook called "useRef", but it is neither a React function component nor a custom React Hook function. Remember, React component names should start with an uppercase letter and React Hook names should start with the ...