difficulty in obtaining information submitted through a form

I'm having an issue with my contact form. I tried testing to see if I can retrieve the values from the form, but it's giving me back:

name: undefined

I'm not sure why it's not working!

Here is the code for the form:

<form  method="POST" enctype="multipart/form-data" action="contact">
  <input name="name" type="text" class="feedback-input" placeholder="Name" />
  <input name="email" type="text" class="feedback-input" placeholder="Email" />
  <textarea name="text" class="feedback-input" placeholder="Comment"></textarea>
  <input type="submit"  action="contact"/>

And here is the request:

app.post("/contact", (req, res) => {

const name = req.body.name
console.log('name:', name)

})

Thank you in advance.

Answer №1

If you're looking to handle file uploads in your Node.js application, consider using the Multer middleware.

Multer is a powerful node.js middleware designed for managing multipart/form-data, specifically catering to file upload functionalities.

For example:

app.js:

const express = require('express');
const multer = require('multer');
const upload = multer();
const app = express();

// Serving index.html on root path
app.get('/', (req, res) => {
  res.sendFile('./index.html', { root: __dirname });
});

// Handling form submission at /contact route
app.post('/contact', upload.none(), (req, res) => {
  const name = req.body.name;
  console.log('name:', name);
  console.log('body:', req.body);
  res.sendStatus(200);
});

app.listen(3000, () => console.log('Server started at http://localhost:3000'));

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form method="POST" enctype="multipart/form-data" action="contact">
    <input name="name" type="text" class="feedback-input" placeholder="Name" />
    <input name="email" type="text" class="feedback-input" placeholder="Email" />
    <textarea name="text" class="feedback-input" placeholder="Comment"></textarea>
    <input type="submit" action="contact" />
  </form>
</body>

</html>

Server logs:

Server started at http://localhost:3000
name: teresa
body: [Object: null prototype] { name: 'teresa', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="057160776076644571606b622b2d666a68">[email protected]</a>', text: 'Best singer' }

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

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

The server is indicating that the validation for the user has failed due to the required field "foo" not being provided in the Node.js

An error message was received with the following details: "User validation failed: email: Path email is required., display_name: Path display_name is required." The error name returned is: ValidationError. The AJAX call code snippet is as follows: f ...

Express is throwing a TypeError because it is unable to access the property 'app', which is undefined

On my nodejs server running the express framework, I have been encountering a random error when making requests. The error occurs unpredictably, usually appearing on the first request and not on subsequent ones. It's challenging for me to identify the ...

Heroku, Express, React, and NodeJS - struggling with HTTPS inconsistency issue

I'm facing an issue with my express routes not working properly when deployed on Heroku. The odd thing is that the routes work fine when accessed via HTTP, but not via HTTPS. Interestingly, they do work on HTTPS with Internet Explorer and Microsoft Ed ...

exploring the capabilities of sockets in PHP, reminiscent of the functionality found in Node.js

I recently downloaded and tried out a basic chat app with Node.js: https://github.com/socketio/chat-example The app is functioning properly. The server-side code is quite straightforward: var app = require('express')(); var http = require(&ap ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

What is the best method for inserting data into multiple databases simultaneously in MongoDB?

As a beginner in the Mean Stack, I find myself in a scenario where I require assistance in uploading data to various databases through mongoose. Any guidance on this matter would be greatly appreciated. ...

Utilizing an NPM Mirror: A Comprehensive Guide

Oh no, the npm registry is experiencing issues once more, causing havoc with executing npm install. Query: What is the alternative method for using npm to fetch packages from npm mirrors? Can you suggest any reliable npm mirrors? ...

Transforming a MongoDB query into an aggregation query?

I am relatively new to MongoDB and I am faced with a scenario where I need to transform a mongo query into an aggregate query. The two collections I have are as follows: items: {_id: "something", "name": "raj", "branch&q ...

Can the information from a form be automatically submitted to the server upon selection?

<div class="modal-body modal-body-step-2"> <form action="prenotazioni.php" method="post"> <div class="input-group"> <input type="radio" name="spettacolo" value="Lo Schiaccianoci">Lo Schiaccianoci<br> ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

Utilizing Angular to Handle Undefined Variables in String Interpolation

Seeking a way to showcase data obtained from an external API on a webpage using Angular's string interpolation. If no data is retrieved or is still pending, the aim is to display 'N/A'. An attempt was made following this method, but encoun ...

What is the best way to display text outside of the current div container?

When I include the "Y" in the code snippet below, $title1 and $title2 are positioned outside of the div and centered against the width of the page. However, without the "Y", the text shifts up and aligns with the address class instead. It's puzzling w ...

Displaying the selected item right at the center of the Flatlist in React Native

I need to ensure that the item selected in the FlatList is always centered. The chosen item should have a different style compared to the others. <FlatList data={items} style={styles.listStyle} ...

What is the best way to retrieve dates from a MySQL database using ExpressJS?

My current task involves retrieving the date value from a MySQL server, but upon printing the result, I encounter an error. In my code, I am able to fetch the date value, however, when attempting to print it, there seems to be an issue with the output. (F ...

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

Transmit a document to the OpenAI API without the need to interact with the file storage system

Is there a way to send file data to the OpenAI API without directly accessing the file system? I have the file contents stored as a string and would like to bypass reading from the file system. The code provided in the OpenAI documentation involves reading ...

Enabling the upload of .sql files in a file input field

I'm working on a file input field that I want to restrict to only accept XML, SQL, and text files. Here's the code snippet I have implemented so far: <input type="file" name="Input_SQL" id="Input_SQL" value="" accept="text/plain,application/x ...

What are the steps to manipulate the data within an EJS file after passing an array through Node.js as an object?

I'm currently developing a simple calendar application using Node.js and ejs. I am working on passing an array of months through express to my ejs file, with the goal of being able to cycle through each month by clicking the next button. How can I imp ...