The message I'm attempting to include in the request is not being transmitted along with the request

Currently, I am facing an issue while using Thunder Client to send requests with a POST method. Despite including the body contents and setting the content-type to application/json in the header, whenever I try to access req.body in the request section, it returns undefined. I am unsure of why this error is happening. Can someone provide assistance with resolving this issue?

const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const Admin = require('../Models/Admin');

//Route 1 : Create an ADMIN Account
router.post('/createadmin', async (req, res)=>{
    
    console.log(req.body)
    res.json(req.body)
       
})

module.exports = router

Answer №1

If you haven't already solved the issue, consider installing and utilizing body parser. Start by running npm install body-parser. Once installed, you can use it as shown below:

Answer №2

Simply install and utilize body parser to send JSON data, as it acts as middleware for this purpose.

//Middleware to parse JSON bodies; include this in your index.js file before defining routes
app.use(express.json());

Here is a sample code structure you can follow:

const connectToMongo = require('./db');
connectToMongo();

const express = require('express');
const app = express();
const port = 3000;

// Middleware for testing fake requests using Thunder client 
app.use(express.json());

// Available routes
app.use('/app/auth', require('./routes/auth'));
app.use('/app/notes', require('./routes/notes'));
app.get('/', (req,res)=> {
    res.send("hello world");
})

app.listen(port, () => {
    console.log("Listening on port: ", port);
})

Hope this explanation proves helpful!

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

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/*/g, ''); I also ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

Can the background color of HTML header text be altered using JavaScript in JQGRID?

Can the background color of HTML header text be modified using JavaScript? Updated: Oops, I forgot to mention that it is for the header text in jqGrid. My apologies for that oversight. ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

Adding a tooltip with a date format to a Highchart graph

Hey everyone, I'm currently working with a Highchart and I want to customize the tooltip value in a specific format. My categories and series are structured as follows: {"Categories":["2015-11-09","2015-11-08""2015-11-15"],"Series":[2,0,2]} Current ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

"Enhance your Angular application with Datatables using $http to fetch and display data

Currently, I'm working on a project with AngularJS where I'm fetching data from the server using the $http service. Here's a snippet of the code: $http({ method: 'GET', url: $rootScope.apiURL + 'getAllClientLocations/ ...

Retrieving a Table Row from a TableView in Titanium Mobile

Does anyone know where the actual tableViewRows are stored within a TableView? When inspecting the TableView, I can see the headings for the Rows but not the Rows themselves. Can someone point me in the right direction to find where these Rows are contai ...

Utilize async/await to send images using node mailer

How can I correctly access mailOptions in the triggerExample.ts file? mail.ts: export const sendNewMail = async (html: string, emails: string[]) => { let smtpTransport = nodemailer.createTransport({ service: "Gmail", auth: { u ...

What is the best way to retain the leading zeros when creating a new Number() in JavaScript?

Hey everyone, I'm running into some issues with this specific function. const incrementString = str => { if (!str.match(/[\d+]$/)){ return str += 1 } else{ return str.replace(/[\d+]$/, match => new Number(match) + 1) } ...

Creating dynamic HTML tables within Highcharts

I need assistance with a webpage I'm working on where tables are dynamically added and removed using checkboxes in HTML. Essentially, when a checkbox is checked, a table is added, and when it's unchecked, the table is removed. My goal is to displ ...

Various Approaches to Transforming Jsonp to Json

I've been experimenting with incorporating JSONP data in a JSON format into my Ruby project. Can you share how you have dealt with this issue based on your own experiences? ...

Navigating to a different page in the app following a document update: a step-by-step guide

I am facing an issue with a page where I am trying to print a specific DIV using the script below... function printReceiptDiv() { var divElements; if (vm.isDLR) { divElements = document.getElementById("DLRreportCont ...

Transform the subscription into a string

When I use the http method to retrieve a single user, the output logged in the console looks like this: this.usersService.getOneUser().subscribe(data => { console.log(data) }); email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Guide on displaying several items from Laravel to Vue through the JavaScript filter method?

I need help transferring multiple objects from laravel to vue and filling my vue objects with information retrieved from the database. This is the data received from laravel: Vue objects to be populated: storeName: {}, storeUrl: {}, appName: {}, ...

Updating JSON files from CI variables in Visual Studio Team Services is crucial for maintaining consistency and accuracy

Visual Studio Team Services offers the ability to modify web.config appSetting parameters using values specified in variables. You can find more information on this process here. However, is there a similar method to update a json file? ...

Nodejs: Dealing with Undefined JSON Objects

I'm encountering issues while trying to access a JSON object. Can you review the code and point out any mistakes I may be making? To provide clarity, I have outlined two cases that illustrate my problem: Below is the JSON data: Case 1: When attemp ...