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

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Tips for updating Nodejs' module dependency to a newer version

Currently, my project utilizes the react-cropper library which includes version cropper ^0.10.0. However, I require certain methods from cropper version 0.11.1. To address this issue, I decided to fork the project to my own GitHub repository in order to up ...

What is the best way to transfer the main-video-wrap div into the video-list-Wrapping div?

Thank you @Kathara for your valuable assistance I have successfully set up the video layout with a picture-in-picture mode option. When I click on a video to move it to the background, it works well. However, I am facing difficulty in moving the entire vi ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

Press the smiley icon and drag it into the designated input box

Is there a way to select and copy a smiley/emoji from a list and paste it into an input field? Although the Inspect Element Q (console log) shows that the emoji is being clicked, I am having trouble transferring it to the input field. Here is the HTML cod ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

What is the best way to cancel Interval in a React application?

I need help with implementing setInterval in my react redux application. Below is the code snippet from FileAction.js export const SetPath = ({ path, location }) => async (dispatch) => { try { let interval; if (pre_path === path) ...

Utilize the function with another function (difficult to articulate)

Apologies in advance for my beginner question. Review the code snippet below: var dt = new Date(t*1000); var m = "0" + dt.getMinutes(); Depending on the t variable (unix time), the output can be one of the following: m = 054 // 54 minutes m = 03 // 3 min ...

Can you explain the distinction between req.query and req.body in Express?

Can you explain the difference between req.query and req.body? In the code snippet below, req.query is being used. What would happen if we replaced it with req.body instead? The following function is triggered by the $resource get function. It checks for ...

Troubleshooting issue with displaying favicons in express.js

Currently, I am working on a simple express.js example and trying to get favicons to display properly. Everything functions correctly when testing locally, but once uploaded to my production server, only the default favicon appears. I have attempted cleari ...

Installing a package from a private repository using a different package name with npm

I'm looking to incorporate a module from a private GitHub repository into my project. To achieve this, I will execute the command npm install git+https://[API-KEY]:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b737c6e607 ...

The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in o ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Persist state in Vue by using the `vue-persistedstate` reducer

Currently, I am utilizing vue-persistedstate with specific modules that are set to be persisted using the path attribute. This setup is functioning smoothly. However, I encountered an issue when attempting to combine it with the reducer. In this scenario, ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

When trying to access document.cookie, an empty string is returned despite the presence of cookies listed in developer tools, and the httpOnly flag is set

There are times when I encounter an empty string while trying to access document.cookie on the login page, despite the following conditions being met: The cookies are visible in the Chrome and Firefox developer tools, The httpOnly flag of the cookie I&ap ...

Looking to incorporate multiple accordion drop down menus on your website? Utilize a combination of HTML, CSS, and JavaScript to

I am experiencing a challenge with implementing multiple accordion menus on my website. Whenever I attempt to duplicate the code, the new accordion menu appears but clicking on the first bar simply scrolls me back to the top of the webpage. Below is the H ...