I encountered an issue when sending a PATCH request via Hoppscotch where the request body content was returned as 'undefined', although the username and ID were successfully

const express = require("express");
const app = express();
const path = require("path");
let port = 8080;
const { v4: uuidv4 } = require('uuid');
app.use(express.urlencoded({extended: true}));
app.set("views engine","ejs");
app.set("views",path.join(__dirname,"views"));
app.use(express.static(path.join(__dirname,"public")));
let posts =[{ id: uuidv4(),username : "Naved",content  : "I love coding",},{id: uuidv4(),username :"Noman",content  : "I love studying",},{id: uuidv4(),username : "Saimoon",content:"Ilovecooking",}] ;
app.get("/posts",(req,res)=>{
    res.render("index.ejs", {posts});
});
app.get("/posts/new",(req,res)=>{
    res.render("new.ejs")
})
app.post("/posts",(req,res)=>{
let {username,content} = req.body;
let id = uuidv4();
posts.push({id,username , content});
res.redirect("/posts");
})
app.get("/posts/:id",(req,res)=>{
    let { id } = req.params;  
    let post = posts.find ((p)=> id===p.id);
    res.render("show.ejs" ,{post})
})
app.patch("/posts/:id",(req,res)=>{
    let { id } = req.params;
    let newContent = req.body.content ;
    let post = posts.find ((p)=> id === p.id);
    post.content = newContent;
    console.log(post);
    res.send("patch request send succesfully");
})
app.listen(port,()=>{
    console.log(`app is listening at the port ${port}`);
});

script.js

The code seems to be working fine. However, there might be an issue with how you are handling req.body.content. Make sure to check for any typos or missing information in your request body.

Answer №1

The issue at hand is with the data parsing process. To resolve this problem, follow these steps:

  1. Start by running npm install body-parser
  2. Next, import it into Express using:
    { const bodyParser = require('body-parser') }
  3. Lastly, apply the middleware like so: { app.use(bodyParser.json()) }

By following these steps, you should eliminate any "undefined" errors and achieve the desired outcome.

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

Searching for the row value of specific data within a table using Javascript

I have a PHP table populated with values, and I want to make two of the table data cells editable. The table headers include: Task, Due Date, Staff, and Department. The values in the table data are retrieved from a database using Laravel Eloquent. &l ...

What is the best way to display all mysql rows in Node.js using handlebars templating?

Here is the code snippet I used to share only the first row (jack) from MySQL: node: const express = require("express"); const app = express(); app.set("view engine","hbs") const mysql = require("mysql") const db = m ...

What is the most effective way to save and access British pound symbols?

Every so often, I face this issue where I end up resorting to a messy workaround. There must be a correct way to handle it though, as it's common to work with UK pound symbols. The dilemma is this: when the user inputs a UK pound symbol (£) into a t ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

Node.js encountered an SFTP error stating "Error: connect: An existing SFTP connection is already defined."

Working within my node.js application, I have implemented ssh2-sftp-client to upload an image every 5 seconds. The initial upload functions correctly, but upon repeating the process, I encounter an error message: node .\upload.js uploaded screenshot ...

AngularUi Mobile Modal List Display

I attempted to implement the code from 32400236/dynamically-generate-modals-with-mobileangularui but encountered issues. I also tried using the following: <div class="access-item" ng-repeat="item in items track by $index"> <a ui-turn-on="$index" ...

Issue: The module './build/Release/scrypt' could not be located

Currently, I am trying to expand my knowledge in JavaScript and Solidity by taking a Udemy course. Unfortunately, the course instructor has not kept the content updated and there is no longer any support available for answering questions. When attempting ...

Issue with child component not reflecting changes when the state is updated

In an attempt to pass a value to a child component, I am encountering an issue where the value does not update when the parent component's value changes. Below is my code: Child Component: class Test extends Component { constructor(props) { su ...

refreshing the webpage's content following the completion of an asynchronous request

I am working on an Ionic2 app that utilizes the SideMenu template. On the rootPage, I have the following code: export class HomePage { products: any = []; constructor(public navCtrl: NavController, public navParams: NavParams, private woo: WooCommer ...

Is it possible to protect passwords internally via URL and AJAX?

During my time at a previous company, we had an internal website that required a password to be entered at the end of the URL in order to view it. I suspect this was done using AJAX, but I am unsure. Even if AJAX was used, I do not know how to code it myse ...

Initiate an Ajax request solely for the elements currently visible on the screen

I am currently facing an issue that requires a solution. Within our template, there are multiple divs generated with the same classes. Each div contains a hidden input field with the ID of the linked target site. My task is to utilize this ID to make aja ...

What is the best way to ensure that your server code, which depends on a database,

Currently, I am working on a NodeJS/MongoDB application that consists of numerous functions. To ensure the accuracy and functionality of these functions, I have implemented several unit tests. One component of my application utilizes Agenda, a task schedu ...

Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious. JS const gri ...

Cancel promise chain after action dispatch (rxjs)

My goal is to achieve the following: this.jobManager .queue( // initiate a job ) .then( // perform additional actions, but stop if `ABORT` action is dispatched before completion ) .finally( // carry out necessary ...

The universal CSS variables of Material UI

Creating reusable CSS variables for components can greatly simplify styling. In regular CSS, you would declare them like this: :root { --box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.3); } This variable can then be utilized as shown below: .my-class { ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

Struggling to retrieve Json data through Ajax in Rails 5

Hey there! I'm currently exploring the world of Rails action controllers with Ajax, and I've run into a bit of a snag. I can't seem to retrieve Json data and display it in my console.log using my Ajax function. The GET method works perfectly ...

The error message "gaq is not defined in opencart 2.0" indicates

While attempting to monitor transactions in OpenCart, I encountered the following error message: Uncaught ReferenceError: _gaq is not defined(anonymous function) This is the method I am using for tracking in my catalog/view/theme/default/template/commo ...

When navigating to a new route using history.push in React, it's important to ensure that the correct state is

My goal is to implement a smooth exiting animation with framer motion based on the user's current route and next destination. I specifically want the background to slide away only when transitioning from route A to route D. To achieve this, I decided ...