Storing POST data securely for a temporary period of time

After retrieving a list of products from a database, everything seems to be functioning properly. However, I am facing an issue when trying to capture the ID when a user clicks on the 'Buy' button. Despite multiple attempts to save the req.body data, I have been unsuccessful.

I experimented with SessionStorage and LocalStorage options, but unfortunately, they did not yield any positive results.

carritoForm: (req, res) =>  {


let obj = JSON.parse(JSON.stringify(req.body)); // req.body = [Object: null prototype] { title: 'product' }
console.log(obj)
res.redirect('index');
}
<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12 bloques">
      <p>Incendios</p>
      <div class="imagen">
        <a href="" target="_blank"><img src="../images/fire.png" alt="" /></a>
      </div>
      <br>
      <p>Lorem ipsum dolor sit amet consectetur adipiscing elit elementum eget congue, tristique sollicitudin enim eu
        nisi ultrices iaculis justo scelerisque, phasellus vestibulum metus rhoncus sapien a integer odio ligula.
        Senectus parturient maecenas conubia netus pharetra felis placerat tincidunt, tortor fusce cras ligula nostra
        cursus augue duis lacinia, nascetur semper a habitasse euismod inceptos vivamus. Sociosqu ante neque morbi
        pulvinar habitasse enim himenaeos, ultrices per orci molestie nisi fames dignissim praesent, lacus iaculis class
        cursus mollis eros.</p>
    </div>

  </div>
  <div class="container">
    <div class="row">
      <br>
      <%  products.filter(function (el) { %>
      <%   return (el.prdCategId === 3); %>
      <% }).map(function(el) { %>
      <br>
      <div class="col-sm-12 col-md-12 col-lg-12 lista-productos">

        <div class="col-sm-4 col-md-4 imgcart">
          <img src="/images/prdImages/<%= el.image %>" alt="">
        </div>
        <br>
        <div class="col-sm-8 col-md-8 agregar-carrito">
          <br>
          <b>Descripcion:</b> <%=  el.description %> <br>
          <b>Precio: $</b> <%=  el.price %> <br> <br>
          
          <form name= 'compras' action="/products/incendios" method="POST" >
            <button name="incendios" value="<%=  el.id %>" type="submit">Buy</button>
          </form>
          <br>

          <br>
        </div>
      </div>

      <% }).sort(); %>

    </div>
  </div>
  
</div>

Upon clicking 'Comprar,' the output correctly displays '{ incendios: '2' }', which corresponds to the pressed button. However, I am unsure about how to store this information.

https://i.sstatic.net/jPimL.png

Answer №1

Instructions for the Controller:

if (req.cookies.cart != undefined) {
console.log('Updating data')
let cartContent = JSON.parse(req.cookies.cart);  // Convert the array to a string in order to add new items
cartContent.push(req.body.item); // Add the new content to the retrieved array
console.log(cartContent)
res.cookie('cart', JSON.stringify(cartContent), { maxAge: (1000 * 60) * 10 }); // Update the cookie
} else {
console.log('Creating data for the first time')
let cartContent = [req.body.item]
res.cookie('cart', JSON.stringify(cartContent), { maxAge: (1000 * 60) * 10 }); // Set the cookie so it is never undefined again
  }

And for the Middleware:

function cartHandler(req, res, next) {
    let cookie = req.cookies.cart
    if(cookie != null) {
        console.log('The cart cookie already exists')
    } else {
         // Create the cookie
let array=[];
res.cookie('cart', JSON.stringify(array), { maxAge: (1000 * 60) * 5 });
console.log('The Cart Cookie was created')
}
    next();
}

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

Provide a numerical representation of how frequently one object value is found within another object value

Account Object Example in the Accounts Array: const accounts = [ { id: "5f446f2ecfaf0310387c9603", picture: "https://api.adorable.io/avatars/75/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b7d7a666 ...

What is the best way to create a DOM element listener in AngularJS?

My goal is to monitor a <div id="please_monitor_me"> to determine if it is visible. If it is not visible, I plan to remove the margin (margin: 0;). I am aiming for no margin when the div is not visible so that it can be shown later with a burger but ...

Testing the Express API with MongoDB on a local machine is successful but encounters a timeout issue on CircleCI

I am facing an issue with testing a RESTful API (built with Express in TypeScript) using Jest. The test passes successfully on my local Windows machine but times out on CircleCI. .circleci/config.ylm version: 2.1 jobs: build: docker: - image: ...

How can I quickly upload a file while load balancing?

I recently developed an application in node js that includes a load balancing feature. I set up separate servers - one for the database and another for managing requests. The issue arises when users upload files using multer in Express, as the file gets up ...

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

Issues encountered with Rails server due to excessive JavaScript calls causing crashes

I have been working on developing a dynamic reporting feature as part of a larger project. The specific issue I am facing is that the functionality works fine for multiple calls but eventually leads to a server crash. I am utilizing mongoid and puma server ...

What could be causing my browser to display "uncaught referenceerror" in this situation?

Just running some browser tests to troubleshoot - everything's smooth sailing until this line is reached: responseJson = JSON.parse(localReq.responseText); So, when I evaluate JSON.parse(localReq.responseText), the correct value comes through. But a ...

Having trouble setting the audio source path in a handlebars file

homepage.html <script> function playAudio(audio_src){ console.log('audio src: ' + audio_src); var player = document.getElementById('player'); player.src = audio_src; player.load(); player.play(); return f ...

(React) Material-UI: The controlled checked state of SwitchBase is being altered by a component, causing it to become uncontrolled

Utilizing the useState hook, I have an array that contains various conditions const [conditions, setConditions] = useState([]) Each element in the array is structured as {condition: "some string", value: boolean} My array is rendered in the following man ...

Transferring an ES6 class from Node.js to a browser environment

I've been exploring ways to bundle a super basic ES6-style class object for the browser. Here's an example: class Bar { constructor(){ this.title = "Bar"; } } module.exports = Bar; While I can easily utilize this in my node projec ...

Storing data in a table created through a belongsToMany relationship in Sequelize and retrieving it. (Solution provided below)

My backend setup includes Node.js, Express.js, and Sequelize for database connections. I have established a many-to-many relationship between Tasks and Keys. I defined the connection between Tasks and Keys using Sequelize as follows: Backend // Task ...

Adding Firebase Data to Vue Table

I am currently utilizing Vue Table JS, which can be found at https://github.com/matfish2/vue-tables-2 <script type="text/javascript"> Vue.use(VueTables.ClientTable); new Vue({ el: "#app", data: { columns: ['name', 'code', ...

Challenges Arising from Using Jade Extends

Recently delving into Jade for a new project and finding it to be quite impressive so far. However, I've encountered a little snag with the Extends feature. The block I created doesn't seem to display when rendering layout.jade. layout.jade: di ...

Tips for using parsley on a dynamically loaded webpage

I'm encountering an issue with applying validation for a datepicker in AJAX loaded content. The validation doesn't seem to work for the loaded content. Can someone please assist me with this? /Script/ function applyValidationForDatepicker(feest ...

Is there a way to convert an array into an object where the first value in the array becomes the name and the properties are an array of the remaining values within subarrays?

Looking to efficiently group elements of a multidimensional array with an unknown list, and transform it into an object while removing duplicate values in the first element of each subarray: For instance, here's the initial array: const arr = [[a, 1 ...

Utilizing innerHTML of the <select> tag with windows.open()

I am working on a feature for my website where users can select one option from a dropdown menu and when they click on the button labeled "connect", it should open a new tab with the corresponding link. Here is the code I have so far: <select name="ch ...

Retrieve the chosen option from a dropdown menu and transfer it to the submit button in PHP

I have a unique situation where I need to extract and store selected values from two separate drop-down menus generated from arrays. The goal is to pass these selected values in the submit button link. For example, if a user selects "123" for email and "t ...

Performing an additional GET request using AngularJS

After successfully running the code snippet, I received the JSON output displayed below. My main focus now is on extracting the cars_url. What would be the most effective method to retrieve the URL (and what approach is recommended), and subsequently initi ...

HTML5 video displaying remaining time before something happens

After troubleshooting, I was able to resolve the issue by implementing the following code: $oVideo.bind('timeupdate', function() { var currVideo = document.getElementById("vPlayer"); var iNow = currVideo.currentTime; var countdown = eval(currVid ...

Triggers are functioning properly; however, they are triggering application errors that are resulting in issues with insert statements

I have included my code below, and overall it is functioning correctly. However, I am encountering errors when the insert statements violate the trigger due to the raise_application_error being triggered. --Drop tables if they were previously created DROP ...