Whenever I issue a POST request, the resulting response comes back as blank

Embarking on my journey with express JS sans experience, I encountered a roadblock here:

server.js:

const express = require('express');

const router = express.Router();
const app = express();

app.use(express.json());

const users = []

router.get('/getUsers', (req, res) => {
    res.json(users);
});

router.post('/postUsers', (req, res) => {
    const newUser = req.body;
    console.log(newUser);
    users.push(newUser);
    res.json(`${req.body.name} is added`);
});

app.use('/', router);

app.listen(3000);

test.rest:

###
GET http://localhost:3000/getUsers

###
POST http://localhost:3000/postUsers

{
    "name": "Joseph"
}

###

Upon making a post request, the response reads as: "undefined is added" with a 200 status.

When initiating a get request, the response is as follows:

[

{}

]

with a 200 status

I reached out to ChatGPT for assistance, but unfortunately, the issue remains unresolved. Apologies if this query seems trivial, as I am genuinely struggling to comprehend the problem at hand.

Answer №1

Unable to determine which HTTP client you are utilizing, let's compare these two tests using cURL:

curl \
    http://localhost:3000/postUsers \
    --request POST \
    --data '{ "name": "Joseph" }'

Results:

"undefined is added"

curl \
    http://localhost:3000/postUsers \
    --request POST \
    --header 'Content-Type: application/json' \
    --data '{ "name": "Joseph" }'

Results:

"Joseph is added"

The Content-Type request header specifies the format of the request body.

Your test.rest file does not contain a Content-Type header, and based on the comparison of behavior with my test that lacks it, it seems likely that this may be causing your issue.

You are sending JSON data through the POST request, but have not informed the server that the payload is in JSON format.

Express middleware, such as express.json, typically relies on the content-type to determine if it should attempt to parse the request body. (It's important to note that there could be multiple body parsing middlewares in a system capable of handling different request body formats.)

Without specifying the content-type in your request, express.json will not attempt to parse it, resulting in an empty object for the body.

A suitable format for your request would likely be:

###
GET http://localhost:3000/getUsers

###
POST http://localhost:3000/postUsers
Content-Type: application/json

{
    "name": "Joseph"
}

###

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 Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

What steps should I follow to set JSONP as the dataType for a request in an Angular $http service?

I have a good understanding of how to use jQuery's $.ajax: $.ajax({ url: //twitter endpoint, method:"GET", dataType:"jsonp", success:function() { //stuff } }); Is there a way to set the JSONP datatype for an angular $http service reque ...

What is the process of retrieving the return value after creating data in Firestore

I have been experimenting with creating data using firestore in the following manner: createData({state}) { return db.collection('items').add({ title: state.title, ingredients: state.ingredients, creat ...

"Encountering an Error with Route.get() when attempting to utilize an imported

I have a function that I exported in index.js and I want to use it in test.js. However, when I try to run node test, I encounter the following error message: Error: Route.get() requires a callback function but got a [object Undefined] What am I doing wro ...

"Rotating the TransformControl in threejs: A step-by-step guide

When the object attached to the transform control rotates, I want the transform control itself to rotate as well. Before the rotation: https://i.sstatic.net/yjTue.png After the rotation: https://i.sstatic.net/2opuU.png As shown in the image, before th ...

What is the reason for the clearInterval consistently functioning after the completion of the function?

Just starting out in web programming and currently delving into javascript and jquery ajax.. This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying the ...

Error: The Vue Class-Based module failed to parse due to an unexpected character '@'

When I run the command nmp run serve on my Vue project, I encounter two errors. I am following a tutorial that uses class-based Vue, but I am facing this error with all my imported Vue files. As a newcomer to Vue, I am puzzled as to why this error is occur ...

What could possibly prevent Jasmine Spyon from being named?

I am currently facing an issue with a failing test even though I have included the necessary calls. One specific area where I am encountering this problem is with the PrimeNG Message Service that I am spying on. Below, you can find the code snippet that I ...

Is there a way to prevent a user who is already logged in from accessing their account on a different browser or tab

My current stack consists of reactjs, nodejs, and redux for user authentication. I am utilizing aws cognito to handle the user authentication process. The main functionality of my app is uploading files from users to an s3 bucket. One of my goals is to p ...

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

Step-by-step guide to populating a JavaScript array with AJAX requests

Having some trouble with populating a JavaScript array using an Ajax request. Here is the code I'm working with. The Ajax portion seems to be running smoothly. function GetColumns() { var customArray = []; $.ajax({ url: '@Url.Con ...

Headers have already been sent to the client and cannot be reset

Although I am relatively new to using nodeJs, I have conducted research to troubleshoot my issue. However, it appears that I am struggling a bit with asynchronous functionalities. I came across a solution that unfortunately did not work as expected. Here i ...

Dynamic-feel Express routing for printing dynamic objects

For my Ubuntu 18 thermal printer, I am sending data to be printed via escpos. My front end server is react. I need to print receipts for different types of information that can vary in structure. Here are some examples: date name customer name customer p ...

What is the best way to create a text input that is both secure and non-editable?

While I am aware of the <input type="text" readonly /> possibility, it is not entirely secure. For example, if there is an input field that must remain uneditable by users, making it "readonly" can still be bypassed by inspecting the code and remov ...

What could be causing SVG to not render in a NEXTJS project upon deployment on Vercel?

Recently, I created a standout single-page nextJS application that was beautifully styled with Tailwind CSS. One interesting feature I added was incorporating the background of a component called SectionWrapper as an svg file. To achieve this, I crafted a ...

Ways to avoid storing repeating paragraphs in JavaScript Array?

Can someone help me with my code? I am struggling to prevent duplicate data from being saved into an array. When I click on any two paragraph elements, the text inside them gets added to an array named `test`. However, I want to avoid saving the same tex ...

leaving code block using Express and Node

My code is displayed below: // Implement the following operations on routes ending with "users" router.route('/users') .post(function(req, res, next) { var user = new User(); user.username = req.body.username; user.p ...

Injecting script into a webpage and initiating an ajax request prior to receiving a response

Trying to accomplish something a bit complex that I believe is feasible, or perhaps someone could offer a suggestion on how to achieve it. At website A, there is a database containing booking data. At website B, the goal is to display information about w ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Using Node to parse XLSX files and generate JSON data

Hello, I am currently utilizing the js-xlsx package which can be found at this link. My inquiry is how to successfully parse an xlsx file with merges and convert it into JSON format. You can view what the excel sheet looks like here. Ultimately, the JSON o ...