What is the best way to access and interpret the information that is being delivered to my express route

For some reason, I am encountering an issue where the data retrieved from req.body.newFullName appears to be empty. The post request is being directed to the correct route, but I am struggling to access the form field data sent via the XMLHttpRequest.

Here is a snippet of the code I have been working with:

Setting up the route in app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser')
var indexRouter = require('./routes/index'); 
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;

Details of the route in users.js

var express = require('express');
var router = express.Router();
/* GET user list */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
/* POST contacts */
router.post("/", function(req,res,next){
  data = req.body.newFullName;

  res.send(data);
})
module.exports = router;

Form details in index.html

...
<form id="contacts">
<label for="FullName">Full Name:</label>
<input type="text" name="newFullName" placeholder="Enter Full Name..."><br>
<input type="submit" value="Submit data">
</form>
...

Javascript that submits the form data

window.addEventListener("load",function(){
    function createContact(){
        var XHR = new XMLHttpRequest();
        var frmData = new FormData(form);
        XHR.open("POST", "http://localhost:3000/users/");
        XHR.send(frmData);
    };
    var form = document.getElementById("contacts");
    form.addEventListener("submit", function(event){
        event.preventDefault();
        createContact();
    });
});

Thank you for any assistance you can provide!

Answer №1

The issue lies in the client-side code; you have set the content type as multipart/formdata, but the server is expecting

application/x-www-form-urlencoded
.

Here is a revised way to send the data:

function addNewContact() {
    const dataToSend = new URLSearchParams(new FormData(form));
    fetch("http://localhost:3000/contacts/", {
        method: "POST",
        body: dataToSend
    })
    .then(response => response.text())
    .then(result => console.log("Result", result))
    .catch(error => console.error(error));
};

If you inspect the request in your browser, you will see that it now correctly displays the parameters instead of raw text.

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 are some ways to create an opaque effect for a DIV element

I've set up a div on the top of my website that spans 100% width and is in an absolute and fixed position. The code for it looks like this: div.header{ height: 60px; width: 100%; position: absolute; position: fixed; top: 0px; ...

Angular checkbox filtering for tables

I have a table populated with data that I want to filter using checkboxes. Below is the HTML code for this component: <div><mat-checkbox [(ngModel)]="pending">Pending</mat-checkbox></div> <div><mat-checkbox [(ngModel ...

Implementing a Comment Section on Your Website with HTML and JavaScript

Currently in the process of setting up my static webpage, and looking to incorporate user comments. I have already written the comment script using HTML, but I am unsure how to write the JavaScript necessary to display the comments beneath each post. Any ...

Modifying a Parent Component's State with React.js

My analytics page is quite extensive. Positioned at the top, there are a few form elements that allow users to select what they want the report to focus on. Beneath these elements, you will find various graphs and tables detailing the data. The layout of ...

Sort values depending on the value of another key

I have a list of different types: const types = ['BAKERY', 'FRUITS', 'RESTAURANT', ...]; The length of this array is not fixed. Additionally, I also have a corresponding category list for each type as shown below: const categ ...

Creating a lively JQ plot and saving it within an HTML file from a .aspx page using C# .net

I am currently in the process of developing a web-based application using Bootstrap. My goal is to save a .aspx page as an HTML file within my application. Upon writing the code: using System; using System.Collections.Generic; using System.Linq; using S ...

Exploring various ways to implement HTTP GET requests within the PrimeVue DatatableUsing a mix

I am facing a challenge where I need to use different GET requests to populate my Datatable with data from separate tables in the Database. Despite trying different approaches, I am unable to figure out how to make this work successfully. I have realized t ...

Guide to displaying a loading progress bar within a div using JQuery

With the help of jQuery's Load function, I am able to load another page into a specific div by calling jQuery.Load("#divid","pageURL"). Whenever I click on an anchor tag within the loaded page, it triggers the jQuery.load("#divid","pageURL") function ...

Link the global to the Vue component

Is there a way to connect global filters, mixins, and additional features to a specific Vue Instance rather than the Vue object directly? For instance import Vue from 'vue.js' import App from './app' import demo from './mixins/dem ...

How do I retrieve the row count of a table after applying filters in Ant Design?

While working with the Table component from Ant-design to search, filter, and sort a large dataset, an issue arose with the "Select all Data" functionality. For instance, clicking on the checkbox at the top of the table only selects the rows currently dis ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

The home page in react router is dynamic rather than static, constantly changing with each use

After creating a page with the help of react-router-dom, I designed a navbar with two links (FormControl, Accordion). The goal was for the main body to change when the user clicks on these links, while keeping the navbar constant and unaffected. Despite m ...

Exploration into the Working Environments of JavaScript and Python

After executing JavaScript code (shown in the top-half) on link1 and python code (shown in the bottom-half) on link2, the diagram below was generated. My inquiry: I noticed that names foo & bar are already present in the global frame (highlighted in ...

MERN stack error: Unable to destructure 'username' property from 'req.body' since it is not defined

While working on user authentication, I encountered an error during testing on Insomnia. The error message read TypeError: Cannot destructure property 'username' of 'req.body' as it is undefined.. I am utilizing passportjs and jwt for ...

How can you extract all values from an ArrayObject using the flatMap method in lodash?

Looking at the Array Object provided, I need to filter the data and group it by a specific key. Here is the Array Object: var data = [{ 'value': [{ 'id': '1', ' ...

Having trouble getting a form to submit to a Rails server using AJAX in IE11 with jQuery

Currently, I'm attempting to transfer data from a form to a Rails server using AJAX. The form consists of two text inputs and one file input. Below is the code for my submit event handler: $("form").on("submit", function(event) { event.preventDefa ...

The new Date function is malfunctioning on Firefox

Could you please explain why this particular function is not functioning correctly in Firefox (V 34 latest)? It appears to be working successfully on all other browsers, but 'DatePosted' is displaying as Invalid Date. Do you have any insights on ...

Expanding the sidebar panel during a redirection

I am facing an issue with the expansion panels in my sidenav. I have successfully been able to track and set their open state as they are opened and closed. However, when a list item within the panel is clicked and redirects to another route, the panel c ...

Extract the JSON data and store it in an array

I'm currently working on parsing a JSONObject using JavaScript. My goal is to parse the object from the JSON and assign it to an array. Any suggestions or help would be greatly appreciated. Here's the code I'm working with: Here is my JavaS ...

How does using a Listener for window.matchMedia inside the $(document).ready() function impact the webpage?

Here is the code snippet I am referring to: $(document).ready(function () { mediaMatchMenu = window.matchMedia("(min-width: 860px)"); mediaMatchMenu.addListener(doMatchMediaResult); }); function doMatchMediaResult(arg) { // "arg&qu ...