There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express");
var app = express();
var morgan = require("morgan");
var mongoose = require("mongoose");
port = 8000;
var User = require("./app/models/user");
mongoose.connect("mongodb://localhost:27017/tutorial", function (err) {
  if (err) {
    console.log("Disconnected: " + err);
  } else {
    console.log("connected");
  }
});
app.post("/users", function (req, res) {
  var user = new User();
  user.username = req.body.username;
  user.email = req.body.email;
  user.password = req.body.password;
  user.save();
  res.send("user created");
});
app.use(morgan("dev"));
app.listen(port, function () {
  console.log("You are listen on port " + port);
});
TypeError: Cannot read property 'username' of undefined at D:\MEAN\server.js:16:28 at Layer.handle [as handle_request] (D:\MEAN\node_modules\express\lib\router\layer.js:95:5) at next (D:\MEAN\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (D:\MEAN\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (D:\MEAN\node_modules\express\lib\router\layer.js:95:5) at D:\MEAN\node_modules\express\lib\router\index.js:281:22 at Function.process_params (D:\MEAN\node_modules\express\lib\router\index.js:335:12) at next (D:\MEAN\node_modules\express\lib\router\index.js:275:10) at expressInit (D:\MEAN\node_modules\express\lib\middleware\init.js:40:5) at Layer.handle [as handle_request] (D:\MEAN\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (D:\MEAN\node_modules\express\lib\router\index.js:317:13) at D:\MEAN\node_modules\express\lib\router\index.js:284:7 at Function.process_params (D:\MEAN\node_modules\express\lib\router\index.js:335:12) at next (D:\MEAN\node_modules\express\lib\router\index.js:275:10) at query (D:\MEAN\node_modules\express\lib\middleware\query.js:45:5) at Layer.handle [as handle_request] (D:\MEAN\node_modules\express\lib\router\layer.js:95:5)

Answer №1

To capture the request body in Express, you can utilize the express.json method which internally relies on the body parser module. For example:

The following code snippet demonstrates how this can be implemented successfully:


app.use(express.json())

Answer №2

In the case that your post request is in JSON format, you will need to parse the body of the request. This can be accomplished by including "body-parser" and utilizing its json method as shown below:

const bodyParser = require('body-parser');
const app = require('express')();
app.use(bodyParser.json());

By using app.use(bodyParser.json()), we are instructing the application to utilize the body parser for all routes.

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

Application utilizing electron technology featuring various tabbed browsing windows connecting to secure websites

Currently, I am in the process of developing my own unique version of a platform similar to using Electron technology. The objective for this app is to provide users with the ability to view multiple URLs simultaneously, such as and , through a tabbed i ...

Limiting a text based on spaces or at the completion of a word within a string or sentence

Currently, I am utilizing a LimitTo filter to generate excerpts of article descriptions for display on the homepage of a website as snippets in the feature section. The LimitTo filter is set at a maximum of "100 characters," but it sometimes cuts off word ...

Accessing files for MongoDB cluster

My goal is to retrieve all the documents from a MongoDB cluster. Even though I have followed code examples from various online sources, I am encountering a minor issue. const MongoClient = require('mongodb'); const uri = "mongodb+srv://<user& ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

Mongodb error occurred due to a duplicate key in the collection with the key value set

I need to set up multiple user accounts. The first account creation is successful, but I encounter an error when trying to create a new account: BulkWriteError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.users.$friends. ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

"Optimizing npm packages for front-end web development in vanilla JavaScript: A guide to bundling for production deployments on

My website is built using vanilla HTML/CSS/JavaScript with ES6 modules and can be deployed to GitHub pages and Netlify. I have set up my site by importing "main.js" in my HTML like this: <script src="js/main.js" type="module" defer&g ...

Disable the functionality of the next and previous buttons for the Bootstrap carousel when clicking on the outer

Here is the code for the carousel: The next/prev button functions under its respective div, how can I stop it? When I click on the div below the carousel, the carousel continues to move as usual. Below the carousel div, there is another one with a tabbi ...

Exploring client-server relationships within the Express framework

Is there a way to transfer an object to JavaScript on the client side? I previously asked this question and received an answer, but because I was unable to check it on my computer, I accepted the response. You can view the details here: Client receive jso ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

Unable to smoothly expand Div in React using Tailwind

I'm facing a challenge in animating a div that contains input elements. I want it to expand smoothly - initially, the text area is small and the other two inputs and buttons are hidden. When clicking on the text area, the input and button should be re ...

Strategies for addressing input range slider cross browser compatibility issues

I have encountered an issue with the slider track while using a customized range slider with CSS. For Mozilla, I utilized the selector for progress (-moz-range-progress) and for IE I used -ms-filler-lower and -ms-filler-upper. Although it works well for b ...

Tips for resizing a tooltip using CSS

I am currently working on customizing tooltips and would like them to display right below the hover text in a responsive manner, with the ability to have multiline text. Instead of spreading horizontally, I want the tooltip to expand vertically based on th ...

Is there a way to reverse the upside-down text generated by OffscreenCanvas.getContext().fillText()?

When using OffscreenCanvas.getContext().fillText() to generate text and then OffscreenCanvas.transferToImageBitmap() to create a map, I noticed that the text appeared flipped upside down when applied as a texture in a threejs project. The image clearly sho ...

"Clicking on a jQuery div will cause it to slide down, and clicking again

I am currently working on this code snippet: $("#right").click(function() { $("#signin").stop().slideDown(300); }); At the moment, it drops down when clicked, but I would like it to slideUp() when clicked again. Your help is appreciated. On a relate ...

What is the best way to retrieve data from a browser using sequelize in a Node.js Express application?

After checking the query results with console.log(), I wanted to view them in the browser. However, when I tried to access the URL (http://localhost:3000/api/menu/all) through my browser, I encountered an error on the console. GET /api/menu/all 200 11.418 ...

React's behavior with Socket.io becomes unpredictable after sending five messages

I'm facing a strange issue while trying to develop a basic chat application using socket.io and React. The application functions as expected for the first 5 messages, but from the 6th message onwards, there is a delay in loading and sometimes previous ...

What is the best way to include a line break in a Pug variable when returning it?

When I use express and pug to inject a text variable in my pug file, the return lines are not being recognized. Even though the string contains several \n characters. How can I replace the line returns with tags in pug? Here is how I inject the va ...

Guide to implementing a variable delay or sleep function in JQuery within a for loop

I've noticed that many people have asked similar questions, but none of the solutions provided seem to work in my specific case. My goal is to incorporate a delay within a for loop with varying time lengths. These time lengths are retrieved from an a ...

Stop the execution of the setTimeout function when the webpage loads in JavaScript

In my postgres database, I have a table named students for storing student information. The structure of the table is as follows: id first_name last_name time_remind 1 pers1 pers1_name 2022-07-30 21:30 2 pers2 pers2_name 2022-07-30 20:38 Current ...