What might be causing req.body to be an empty object?

I'm currently diving into the world of XMLHttpRequests. My goal is to send some input data to the server, but when it reaches its destination, the Object appears empty as if it were {}. I've noticed that by commenting out the setRequestHeader section, the object gets printed correctly, yet I encounter an error stating that it should be open in the browser. However, placing it after the open() statement causes it to malfunction again and the object arrives empty. I've even attempted JSON.stringfy on the variable before sending it, but with no success.

//server.js
const express = require('express');
const app = express();
const cors =require('cors')

app.use(cors())

app.use(express.urlencoded({extended:true}))

app.post('/phrases', function(req, res) {
    console.log(req.body);
    const phrase = new phrase(req.body);
    // console.log(phrase);
})

app.listen(3000, () => console.log('listening on 3000...'));

//script.js
var form = document.getElementsByTagName('form')[0];

const xhr = new XMLHttpRequest();
// xhr.setRequestHeader('Content-Type', 'application/json');

form.onsubmit = (e) => {
    e.preventDefault();
    const thisName = form.elements[0].name;
    const thisValue = form.elements[0].value;
   
    const phrase = {[thisName]:thisValue};
    console.log(phrase)
    xhr.open('POST', 'http://localhost:3000/phrases');
    xhr.send(phrase);

}; 


<!-- index.html -->
    <form action = "http://localhost:3000/phrases" method="post">
        <label for="favoritephrase"> What's your favorite phrase?
            <input id= 'phrase' type="text" name="favoritephrase">
            <button id= 'send-phrase' type="submit">Send</button>
    </form>

Answer №1

req.body remains empty by default because the incoming request body is not automatically read. To access and parse the body data, you need middleware that matches the content-type of the incoming request.

In your xhr call, it's crucial to determine the content-type for sending the data, format the data accordingly, and set the header correctly. Only then can you add appropriate middleware to your server to read and parse the body, allowing you to access it in the req.body.

If you plan on sending the data as JSON, ensure to set the content-type to JSON on the client side and format the data as JSON:

form.onsubmit = (e) => {
    e.preventDefault();
    const thisName = form.elements[0].name;
    const thisValue = form.elements[0].value;
   
    const frase = {[thisName]:thisValue};
    const xhr = new XMLHttpRequest();
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.open('POST', 'http://localhost:3000/frases');
    xhr.send(JSON.stringify(frase));

}; 

Next, include this middleware before your /frases route handler on your server:

// read and parse incoming JSON request bodies
app.use(express.json());

This will properly handle and parse the data with an application/json content-type sent from your Ajax request.

P.S. It is recommended to use the fetch() interface instead of the XMLHttpRequest API for writing new code due to its ease of use and more modern design using promises.

Answer №2

Make sure to establish the header once the open function is executed

xhr.open('POST', 'http://localhost:3000/frases');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(frase);

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

Instructions for parsing a JSON string obtained via HTTP and iterating through its contents

I'm currently working with Scala and Swagger and I'm struggling with how to iterate through the values in the JSON response and utilize those values for validation and other purposes. The JSON string returned from a HTTP GET request has the foll ...

Is there a time limit for processing express requests?

My API runs a child process upon request and returns its final output. The processing can take anywhere from 5 to 30 minutes, which is acceptable. However, Express drops the connection after some time and only logs POST /api/v1/check - - ms - -. This means ...

How should one properly handle the parsing of this JSON object in C#?

Here is the JSON object I am receiving from a GET request: { "data": { "valve_maker": [], "water_volume": [ "15L", "20L", "..." ], "cylinder_manufacturer": [ "Tianhai" ], "qc_stamp": [ "TS" ...

Preventing the need to reset JavaScript text inputs

I'm encountering a strange issue in my code. I'm developing a graphing calculator that requires users to enter multiple expressions for evaluation. I have a text input and a button that adds a new input to the parent div whenever it is clicked: d ...

Encountering an issue in REACTJS where the error message "TypeError: navigate.push is not a function"

I'm currently working on setting up the homepage for my react.js website. Everything looks good with my layout and the code compiles successfully. However, when I try to click on a button, I encounter an error on the live website application: TypeErr ...

How to Handle an Empty Route with a Trailing Slash in Backbone Routing?

While I am aware of the potential SEO issues that come with duplicate content, my project is not currently focused on that aspect. Looking at my backbone router configuration, here it is: routes: { "": "startOrder", "order/:orderNumber/:stepName" ...

Analyzing the list of paths that are passed to the function

I am looking for assistance in creating an asynchronous "getTypes" function that can analyze a list of paths and return an array describing the type of content in each path. The function should handle all cases efficiently and in case of any errors during ...

Exploring the possibilities of page manipulation using React Native WebView

I'm encountering an issue with my implementation of react-native-webview. When I use it to open a webpage, the audio doesn't start playing automatically. Instead, I have to press a button for it to play. Is there a way to make the audio play dire ...

Obtain Beautifully Formatted JSON from MVC 3's JsonResult

Scenerio Programming Language: C# Platform Version: Microsoft .Net Framework 4.0 Operating System: Windows 7 Professional (64-bit) Constraints: Microsoft MVC.Net 3.0 Issue Description In my current development tasks, I often need to inspect JSON ...

Approach for calculating the total of values during an iteration

I am working with the array $scope.otherDetailsData [0] object amount: 29.9 code: "012" currency: "BRL" payedDate: "2016-11-10" roDate: "2016-08-01" type:"OTHER" [1] object amount: 39.9 code: "013" currency: "BRL" payedDate: "2016-11-11" roDate: "2016- ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

toggle switch for numerical input

Whenever the "Qty" radio button is selected, I need to activate an input box that accepts numbers. Conversely, when the "rate" radio button is clicked, I want to disable this input box. This is how I designed it: <input type="radio" class="radioBtn" ...

gathering identical objects in the collection

I need to calculate the total time of the specified objects and display it in a single list. Here is the object data: var list = [ { 'user': 'Tom', time: 270547 }, { 'user': 'Alex', time: 82081 }, { 'user&apo ...

Real-time Exchange of HTML Data Forms

Hey everyone, I am completely new to programming and I would really appreciate your guidance through this process. Let's imagine a scenario where two users need to communicate through HTML forms. The first user fills out an HTML form (first name, la ...

How can I retrieve the initial IP address from the 'X-Forwarded-For' using a Log Insight Query?

Can someone help me with extracting the initial IP address from the given data: X-Forwarded-For":"1.1.1.1, 2.2.2.2? This is the query I am currently using: fields @timestamp, @message | filter @message like /Endpoint request body after transform ...

changing the elements' classes by using a carousel

Having trouble with a custom carousel and unable to use the standard Bootstrap carousel. This is how my code is structured: Images: <img src="1.img"/> <img src="2.img"/> <img src="3.img"/> Prev / Next buttons: <div class="left ...

Utilizing the Express.js Passport package for both Facebook and Local login authentication

I am currently utilizing the Passport middleware for ExpressJS, and I'm facing a challenge in implementing both the passport-local strategy and the passport-facebook strategy simultaneously. My goal is to enable users to create an account on my websit ...

Tips for displaying a specific PDF file using the selected programming language

As a newcomer to react.js, I have a question regarding my system which allows the user to select the default language. If the chosen language is French, there is a specific URL that needs to be included in the Iframe path. For Spanish, it's a specific ...

Backup your MySQL database using ExpressJS and SequlizeJS libraries

Hey there! I'm currently working on an ExpressJS RESTapi project that uses SequlizeJS as its ORM for a MySQL database. I need to figure out how to create a backup of the database and store it locally. Any suggestions on how to accomplish this within E ...

Why won't my code display in the div element as expected?

I am in the process of developing a gameserver query feature for my website. The objective is to load the content, save it, and then display it later. However, I am encountering an issue with the echoing functionality. The element is selected by its ID and ...