Warning: An unhandled promise rejection has occurred due to a TypeError, as the property 'title' cannot be read since it is undefined

I am encountering an error related to the router.post("/") function in my JavaScript, express, ejs, and MongoDB project.

The main objective of this post request is to enable users to save a blog post, which will then redirect them to the main page ("/"). As a beginner in this technology stack, any assistance would be greatly appreciated!

const express = require("express");
const Post = require("../models/post");
const router = express.Router();

// app.set("view engine", "ejs");

router.get("/new", (req, res) => {
  res.render("posts/new", { post: new Post() });
});

router.get("/:id", async (req, res) => {
  const post = await Post.findById(req.params.id);
  if (post == null) res.redirect("/");
  res.render("posts/show", { post: post });
});

router.post("/", async (req, res) => {
  let post = new Post({
    title: req.body.title,
    description: req.body.description,
    link: req.body.link,
  });
  try {
    post = await post.save();
    res.redirect(`/posts/${post.id}`);
  } catch (error) {
    console.log("failure to create new post");
    res.render("posts/new", { post: post });
  }
});

module.exports = router;

**EDIT #1 - The following code snippet is from my server.js file, which I suspect is related to the error **

const express = require("express");
const mongoose = require("mongoose");
const Post = require("./models/post");
const PostModel = require("./models/post");
const postRouter = require("./routes/post");
const app = express();
require("dotenv").config();

app.set("view engine", "ejs");

const connect = () => {
  const un = process.env.MONGO_USER;
  const pw = process.env.MONGO_PASSWORD;
  return mongoose.connect(
    `mongodb+srv://${un}:${pw}@personalblog.b6isg.mongodb.net/PersonalBlog?retryWrites=true&w=majority`,
    { useNewUrlParser: true, useUnifiedTopology: true }
  );
};
connect().then(async (connection) => {
  const createdPost = Post.create();
  console.log(createdPost);
  console.log(connect());
});

app.get("/", async (req, res) => {
  const post = await Post.find().sort({ createdAt: "desc" });
  res.render("posts/index", { post: post });
});

app.use("/posts", postRouter);

app.use(express.urlencoded({ extended: false }));
app.listen(4000);

Answer №1

The issue might be due to the req.body coming in as undefined in your router.

To address this problem, consider adding the following code snippet to your app.js:

app.use(bodyParser.urlencoded({
    extended: true
}))
app.use(bodyParser.json())

After making these changes, try sending the request again.

Answer №2

According to your coding structure, you are utilizing the body as a JSON request

router.post("/", async (req, res) => {
  let post = new Post({
    title: req.body.title,
    description: req.body.description,
    link: req.body.link,
  });
  try {
    post = await post.save();
    res.redirect(`/posts/${post.id}`);
  } catch (error) {
    console.log("Failed to create a new post");
    res.render("posts/new", { post: post });
  }
});

Therefore, in your server js, set up middleware for JSON instead

// URL encoded parsing
app.use(express.urlencoded({ extended: false }));
// JSON parsing
app.use(express.json());

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

Modify a website link using Javascript by detecting two separate button clicks

I am seeking a way to dynamically change the src attribute of different images on a house depending on which button has been clicked. There are two groups of buttons: The types of house parts, such as windows, doors, garage, soffits, and gutters. The col ...

Tips for transferring information between two distinct pages utilizing the jQuery POST technique

I'm dealing with two PHP files called card_process.php and payment.php. My goal is to transfer data from the cart_process page to the payment page. Here's a snippet of the code: In cart_process.php: $paynow = "<button type='submit' ...

jQuery validation does not work properly when using .element(element) in a custom method

I am struggling with a custom rule that is supposed to check dependencies by validating other inputs it relies on. However, when I implement this validation, it seems like all other validations are being ignored. Here is my custom validation rule: jQuery ...

Encountered "Function undefined error when invoking within a map in TypeScript"

In my function, there is a map that looks like this: mainFunc(){ // other logics data.map(function (item) { item.number = Math.round(item.number); item.total = item.last - item.first; item.quantity= item?.quantity ? quantityRange(ite ...

Issue with dropdown component in material ui version v1.0 beta 26 encountered

Currently, I am encountering an issue with the dropdown component while using Material UI v1.0 beta.26. In this updated version, you are required to utilize the Select component along with MenuItem. Although my dropdown is successfully populated upon rend ...

javascript: window.open()

I am currently using VB.NET 2005 and I have a requirement to launch a new browser window using Process.Start(). The challenge is that I need to specify the size of the browser window, for example, height:300 and width:500. Process.Start("firefox.exe", "ab ...

Guide to testing Higher Order Components with React Testing Library

I've created a higher-order component (HOC) that adds props to a component for handling network requests and passing down data as props. Below is a simplified version of the HOC: export const withTags = (Component) => { class WithTags extends Pur ...

Best practices for securing passwords using Chrome DevTools in React development

React developer tool inspector Is there a way to prevent password values from appearing in the inspector as a state when handling form submissions in ReactJS, especially when using Chrome's React developer tool? ...

Connecting two tables in an express API

Currently, I am in the process of developing an API using Express.js. At this stage, my initial tests are functioning correctly. My goal now is to retrieve values from two separate tables. For example, consider the following 2 tables: Table_A Id: 1, Name: ...

Having difficulty merging information from one mongoose model to another

Novice Developer here. I am currently working with 2 schemas: var categorySchema = new mongoose.Schema({ name: String }); var subCategorySchema = new mongoose.Schema({ name: String, parent: { name: String, id: { ...

Is there a way for me to prevent the setTimeout function from executing?

I have a function that checks the status of a JSON file every 8 seconds using setTimeout. Once the status changes to 'success', I want to stop calling the function. Can someone please help me figure out how to do this? I think it involves clearTi ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...

Utilize data from a dynamically loaded component within a parent component in Vue.js

In my Vuejs application, I've implemented a wizard-type flow with dynamically loaded components. The parent component contains the Save button, while the child components have all the text fields. Upon clicking the Save button, I need to achieve two m ...

Rotating through elements in timed intervals

After exploring various examples of how to show/hide divs with a JavaScript timeout, I am still unable to resolve my specific issue. I currently have six divs that I want to cycle through sequentially every 10 seconds, starting with div #one. Although my ...

Creating a stylish navigation bar with custom components using Material UI and React

I've been experimenting with the BottomNavigation component from Material UI, but instead of using labels and text, I want to incorporate custom-made ImageButton components. Here's the code snippet from Material UI: import React from 'rea ...

What is the best way to link layout images in express.js in order to easily access them from within nested directories?

Currently, I have an express.js app that utilizes ejs (using jade for newer projects) and I am faced with a challenge in finding a clean and appropriate solution. In my layout.ejs file, I have included my header and footer. Thus far, my site has mostly be ...

Troubleshooting Issue with Query Functionality in MEAN App's Find Request

I'm facing some challenges while working with queries in my MEAN App. Specifically, I am attempting to retrieve data that matches the input entered into a search field: $scope.searchInput = function(search){ $http({ method: 'GET', url: ...

Can we find a relationship between the status code '401 (Unauthorized)' and the absence of 'deserializeuser not called'?

http://localhost:3005/api/users/survey 401 (Unauthorized) client - "This code is for displaying a modal when the user hasn't completed the survey." useEffect(() => { async function getSurvery() { const response = await fetch ...

Adjusting webpage background with JavaScript

I've been struggling with this for the past six hours and can't seem to get it right. I've checked out various solutions on Stack Overflow, but nothing seems to work. What am I missing here?!? My html5 page doesn't have a background an ...