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

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Crack open a JSON object

I am struggling to parse a JSON object. It seems like the code is not working, can you help me? var mock_data = { "available": [{ "UserID": 7, "UserName": "Manoj", "Language": "Java", "Score": 9, "TimeLimit": 4.0 }, { "UserID ...

Creating an element in JavaScript with a designated ID is a

I'm working on creating a JavaScript array that holds 3 elements: var employees = [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] To iter ...

monitoring the winstonjs logs and inserting additional parameters

Can an argument be injected into a log, like error, debug, or info, using the configuration of winston (createLogger)? I want to intercept the log and include an object in each log entry. ...

jQuery performs perfectly in Chrome but encounters issues in IE9/IE8 and other older versions of Internet

I've implemented this lengthy jQuery script to enable dynamic dropdown loading and updating when selections are changed. However, I'm facing issues in Internet Explorer where the script loads the dropdowns initially but doesn't trigger oncha ...

Is there a way to specifically target CSS media queries if the device resolution is similar, but the device screen size (measured in inches) varies

I possess two distinct gadgets. 1. T2 light - LCD : 15,6“ Resolution : 1920 × 1080 Device pixel ratio : 1.4375 CSS media query target : width = 1336px 2. T2 mini - LCD : 11,6“ Resolution : 1920 × 1080 Device pixel ratio : 1.4375 CSS media query t ...

Process called gulp useref eliminates certain files from the pipeline

Is there a way to exclude the gulp.src file from output? I am aiming to bundle only JavaScript and output .js files, not HTML. The following blocks in base.html are utilized for bundling JavaScript with gulp-useref: <!-- build:js app.core.js --> &l ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

Using jQuery to drag a div and drop it to swap out an image in a different

I am looking to implement a drag and drop function where I can move elements from one div to another, each containing different images. However, I want the image displayed in the second div to change based on the element being dragged. For example: When d ...

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

Ways to retrieve output from a JavaScript function

How can I successfully return the result from response.on within the signIn function? const signIn = async (password) => { var request = new DeviceAuthQuery(); request.setPassword(password); var response = client.authenticate(request, {}, (err, ...

Issue encountered: org.json.JSONException - Index 2 exceeds the accepted range

Hello, I am currently dealing with a simple JSON error that says org.json.JSONException: Index 2 out of range. Can someone help me solve this issue? Here is the snippet of my JSON: [ { "cat_id": 593 "title": "Allergy and Immunology", "sub_cat" ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use mom ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

App Engine serves up JSON data using JsonProperty

I appreciate how the JsonProperty in Python seamlessly encodes data into JSON when saving to the database and decodes it upon retrieval. However, I am seeking a solution to directly send raw JSON data to a web browser without the need for further encodin ...