I recently started learning about Node JS and I am attempting to make a post to a particular request, but I keep encountering an error

Here is the function I use to fetch data:

let a = showbtn.addEventListener('click',function(){
    list.innerHTML='';
    fetch('http://localhost:3000/products')
      .then ( response =>response.json())
      .then( data => {
         data.forEach( product => {
            let li =document.createElement('li');
            li.textContent=` ${product.id} - ${product.name} - $ ${product.price} `;
            list.appendChild(li);
         });
      })
})

This is how my App.js file is structured:

let express=require('express');
app=express();
//after completing index.html we set index.html as a home page like this by introducing public client folder:
app.use(express.static('public'));
productsArray=[];
//every products must have an id number:
let id=1;
app.use(express.json());

//showing all products:
app.get('/products',(req,res)=>{
    res.send(productsArray);
    

})
//creating ptoducts(posts):
app.post('/products',(req,res)=>{
    let newProduct=req.body;
    newProduct.id=id;
    id++;
    productsArray.push(newProduct);
    res.send('new product created by newProduct=req.body and added to array by push method: Array.push(newProduct)')

    
})

This is the HTML content in my file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>shop</title>
</head>
<body>
    <h1>shop</h1>
    <h2>show all products</h2>
    <button class="show-products">show</button>
    <!-- //everyl ist item is a separate product -->
    <ul class="product-list"></ul>

<!-- //.................................................................... -->
    <h2>add product</h2>
    <form  class="add-product-form">

    <p>
        <label for="add-product-name">
            product:
         
        </label>
        <input id="add-product-name" type="text" >
    </p>


    <p>
        <label for="add-product-price">
            price:
         
        </label>
        <input id="add-product-price" type="text"  >
    </p>
 
    <button>add</button>

    </form>
<script src="js/script.js"></script>
</body>
</html>

Encountering an issue where after entering text into the product and price fields on localhost:3000, clicking the show button displays this result:

1 - undefined - $ undefined

The first one represents the ID, followed by the product name being displayed as undefined along with the respective price also showing as undefined. It seems there's an issue with retrieving the values correctly but finding it challenging to troubleshoot and rectify.

Your assistance is greatly appreciated. Thank you.

Answer №1

When working with POST requests in express, it is essential to utilize body-parser

Learn more about body-parser here.

npm install body-parser

var bodyParser = require('body-parser')

This code snippet is from the official documentation:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Answer №2

To modify the JavaScript file, eliminate all semicolons and substitute them with commas

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

The error message "SyntaxError: Import statements can only be used inside a module when trying to import

I am currently working on a node.js (express.js) project where I am attempting to wrap axios in order to create a HttpClient. Here is my implementation: import axios from 'axios'; const httpClient = axios.create({ baseURL: 'http://locahost: ...

The error message "TypeError: is not a function" has been encountered while using NodeJS with Typescript

I am encountering an issue in nodeJS with TypeScript. I have tested my code both without and with this.: this.funktion2(); ^ TypeError: this.funktion2 is not a function funktion1(); //case #two ^ ReferenceError: funktion1 is not ...

Determine the number of JavaScript functions present on a webpage using JavaScript

Hey there! I'm interested in counting the javascript functions on a specific page and then sending this count via ajax. Do you think it's possible to do this using javascript? What would be the best approach? Thanks in advance! Just to explain f ...

Is there a way to combine properties from two different objects?

I am working with several JavaScript objects: { x: 5, y: 10, z: 3 } and { x: 7, y: 2, z: 9 } My task is to add these two objects together based on their keys. The resulting object should look like this: { x: 12, y: 12, z: 12 } Do you ...

Can you explain the distinction between key and id in a React component?

I have included this code snippet in the parent component. <RefreshSelect isMulti cacheOptions id='a' key = 'a' components={makeAnimated()} options={th ...

Issues encountered while trying to export a document to local Google APIs

I'm encountering difficulties downloading files from Google Drive using the Googleapis Node library. Here is my current code that is functional: drive.files.export( { auth: this.jwtToken, fileId: fileId, mimeType: 'ap ...

Display elements that are unique to one array and not found in another array using React

I am working on a feature where users can select fruits from an array called fruits, and the selected fruits will be stored in another state array named user_fruits. Once a fruit is selected by a user, it should not be available for selection again. fruit ...

Tips for aligning text in the middle of a line

I am currently attempting to design a page separator that includes text nestled between two horizontal lines. Despite my efforts, I am struggling to achieve the desired effect of having the text contained within these lines. You can view my progress in JS ...

Tips for integrating Bootstrap with ReactJS

As a newcomer to the world of React.js, I find myself unsure of how Bootstrap integrates with React. While researching, I came across npm packages like reactstrap and react-bootstrap, but I still don't quite understand. The HTML code seems to be gene ...

Creating cross-browser gradients using CSS (potentially with the help of Compass)

Looking for a CSS gradient solution that is compatible with all major browsers, including IE7+? Preferably without the need to write extensive code or use custom image files? Compass's gradient mixin doesn't support Internet Explorer, so any alt ...

Prevent users from submitting multiple times using Angular

There is an issue where users click the save button multiple times, causing a queue of requests to be submitted and resulting in the creation of duplicate data. How can we prevent this on the front-end so that only one request is submitted even if the butt ...

Having trouble adding a tag with npm

Utilizing the how-to-npm tutorial to grasp some fundamental npm commands, I encountered an error while attempting to add a tag to a module. This occurred when running the command: npm dist-tag add <a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Struggling to set a background image for multiple div elements

Hey everyone! I'm working on a small school project website and I've run into an issue with the background on multiple div elements. Here's my HTML code snippet: <div class="bloc-1-text"> <h3> </h3&g ...

I am unable to modify the suffix located beneath the price of the product

Although I am not well-versed in PHP, I managed to create a code to display parcel descriptions below the price of products. The issue I am facing is that my code is calculating too many decimal places and not displaying the default currency, which should ...

Increment and decrement values using Jquery for dynamically generated fields

Recently, I came across some straightforward code that allows for incrementing and decrementing fields. However, the issue I am facing is that I am unsure about how many fields will be generated (as they are generated by MVC). My question is, how can I int ...

Error thrown: The client password must be in string format for SASL SCRAM-SERVER-FIRST-MESSAGE

Attempting to link my database with express, encountering this error message on PostgreSQL: throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string' If anyone has successfully resolved this issue before ;) ...

Using HTML to showcase various prompt messages based on the screen resolution

For the button click event, when clicked on desktop screens it will show a prompt message saying 'Hi'. On the other hand, when clicked on mobile screens, the prompt message displayed will be "Hello". ...

Concealing spinner controls on HTML Ionic number input

Seeking a foolproof method to conceal spinner buttons on an HTML template for Ionic's number input field. Showcased below is the HTML code that exhibits an input with spinner buttons: <ion-input type='number'></ion-input> The ...

Discover the XPath of a post on a Facebook page with the help of HtmlUnit

I am trying to fetch the xpath of a Facebook post using HtmlUnit. To better understand my goal, you can check out these two related questions: Supernatural behaviour with a Facebook page HtmlUnit commenting out lines of Facebook page To replicate my pro ...

Tips for importing a PDF file and storing it in your database

I have a project using Angular 7, .NET Framework, and MongoDB where I am creating user profiles. One of the requirements is to allow users to optionally upload a PDF file along with their other information. This is what I have implemented so far: <labe ...