JSON.parse not returning

I’ve just started to get into JSON with JavaScript but when trying to use this in an actual project all I got for the return was [object Object]. The code below shows the return I want to get in the variable games data.

let games = '{"games": [{"name": "PUBG","desc": "Original widely popularised by `The bridge incident.` PUBG is a shooter with many fun modes and distinctive gameplay.  "}]}'
JSON.parse(games)

alert(games[0].name);

//Should output PUBG

I don’t know why it won’t return even after using the other questions on it here at Stack. I’ve tried using this question and other sites as a guide: Accessing json objects with no name (Needs to be an alert)

Heroku with redis continously logs Informations and also socket error

I use heroku, redis and nodejs with express. After I setup the redis on my node app, I was able to cache data. However, in the Heroku log console, i get continously logs in the following format:

2024-04-21T18:54:09.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-octagonal-55498 sample#active-connections=3 sample#load-avg-1m=3.63 sample#load-avg-5m=3.3 sample#load-avg-15m=3.96 sample#read-iops=0 sample#write-iops=0 sample#memory-total=16070704kB sample#memory-free=8981520kB sample#memory-cached=3846880kB sample#memory-redis=553608bytes sample#hit-rate=0.86207 sample#evicted-keys=0

It doesn’t look like an infinite loop, it is logging these info from 1 minute to another.
But between, I get the following:

2024-04-21T18:55:20.062782+00:00 app[web.1]: Error connecting to Redis: SocketClosedUnexpectedlyError: Socket closed unexpectedly
2024-04-21T18:55:20.062819+00:00 app[web.1]:     at TLSSocket.<anonymous> (/app/node_modules/@redis/client/dist/lib/client/socket.js:194:118)
2024-04-21T18:55:20.062820+00:00 app[web.1]:     at Object.onceWrapper (node:events:633:26)
2024-04-21T18:55:20.062820+00:00 app[web.1]:     at TLSSocket.emit (node:events:530:35)
2024-04-21T18:55:20.062821+00:00 app[web.1]:     at node:net:337:12
2024-04-21T18:55:20.062821+00:00 app[web.1]:     at TCP.done (node:_tls_wrap:657:7)
2024-04-21T18:55:20.071389+00:00 app[web.1]: Connected to Redis

The error allows redis to reconnect. I am able to continue using my cache.

I need to mention that this is my first time I use redis, especially in production. The initiation of the redis library is created straight into my express project app.js file.

import redis from 'redis';
const REDIS_URL = process.env.REDIS_TLS_URL || process.env.REDIS_URL;

export const redisClient = redis.createClient({
    url: REDIS_URL,
    socket: {
      tls: true,
      rejectUnauthorized: false
    }
});
redisClient.connect();
redisClient.on('connect',   () => console.log('Connected to Redis'));
redisClient.on('error',     error => console.error('Error connecting to Redis:', error));

Regarding the use , I use the redisClient in controllers.
For example

        const cachedTargetMuscles  = await redisClient.get('targetMuscles');

Can you please help me find what is wrong?
Many thanks, Daniel

Unexpected result when using setInterval in Firefox

Trying to diagnose an issue that I run into writing a bookmarklet for my personal use. Long story short is, it works perfectly fine on Chrome and Chromium based browser but behaves unexpectedly when executed in Firefox.

Using simple code to illustrate problem:

javascript:var number=0;function test(){console.log("The number is " + number);number++;};setInterval(test,1000);

Whenever executed in chromium based browser, the code works as intended, counting numbers from 0 up in the console until clearInterval is issued. In Firefox, however, it just returns the ID (which makes sense) but instead of counting in the console it writes the ID to the document.body, overwriting existing html.

It seems like the issue only arises with setInverval method because the code below works just fine

javascript:console.log("The number is whatever");

For clarification we’re talking about pure HTML + JS.

Any tips and help is appreciated. Thank you for your time.


Works:

javascript:console.log("The number is whatever");

Does not work:

javascript:var number=0;function test(){console.log("The number is " + number);number++;};setInterval(test,1000);

setInterval returns the interval ID but overwrites existing document.body with said ID.

Cloning Live Website App to Run on LocalHost (WebPack & _Next)

I’ve been trying to download all the assets from a website with the goal of figuring out how it works and reverse engineer them to build something similar.

I’ve tried with 3 similar websites, and haven’t been successful. All the sites have chunks and this is where I get confused. I used the plugin “ResourcesSaver” to download all the files but can’t figure out how to run them after.

For example this site under inspect>sources the folder “_Next/Static” has all the chunks and code for each page. Then under Network I found _buildManifest.js and it seems to connect them together.

The same for this site which has a lot more chunks and files.

I’ve used ResourcesSaver to download all the files and run them on VS but continually get errors and assume I’m doing multiple things wrong.

How would someone download a website like this and run it similarly to how you can with simple HTML websites?

noUiSlider overlaps with elements below it which causes interaction issues

I am using noUiSlider for a project where I have multiple sliders on top of another. I noticed that the HTML elements lose interactivity if there is a slider on top of it and after a lot of digging I realised it’s because the pips element overlaps with the slider below it.

I tried a bunch of CSS commands to change the z-index (after setting position to something non-static) but none of them worked. I also tried changing the height of the slider to compress it (including with !important), but all of those seem to get overwritten by the libraries’ code.

I have temporarily added 5 <br> which seems to have worked, but since I have many sliders the section now takes up too much space which is why I was hoping to find a different work around.

I suspect the noUi-pips noUi-pips-horizontal class to be the main culprit but none of my CSS tags targeting that seem to be able to override the height. Any help/insight is appreciated!

I’m facing an error that pops up with cannot POST/addTask

Here is the code of my index.js. I think the problem is here but I spend a week to find the problem and I’m still stuck on this. I hope some of you guys help my with that. I’m following the FullStack video of Syed Muhammad Danish. It’s an application for build a To-Do-List.

require("dotenv").config();
const express = require("express");
const app = express();
const fileUpload = require("express-fileupload");
app.use(
  fileUpload({
    extended: true,
  })
);
app.use(express.static(__dirname));
app.use(express.json());
const path = require("path");
const ethers = require("ethers");

var port = 3000;

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

app.get("/index.html", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

// Connect with the blockchain things
const API_URL = process.env.API_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const CONTRACT_ADDRESS = process.env.CONTRACT_ADDRESS;

// In order to communicate with the smart contract you have to have de contract address and the ABI
const { abi } = require(`./artifacts/contracts/TaskDoList.sol/TaskDoList.json`);
const provider = new ethers.providers.JsonRpcProvider(API_URL);

const signer = new ethers.Wallet(PRIVATE_KEY, provider);

const contractInstance = new ethers.Contract(CONTRACT_ADDRESS, abi, signer);

app.post("/addTask", async (req, res) => {
  var task = req.body.task;
  console.log(task);

  async function storeDataInBlockchain(task) {
    console.log("Adding the task in the blockchain network... ");
    const tx = await contractInstance.addTask(task);
    await tx.wait();
  }

  await storeDataInBlockchain(task);
  res.send("The task has been registered in the smart contract");
});

app.listen(port, function () {
  console.log("App is listening on port 3000");
});

If you want to upload more code, just tell me. Thanks y’all

I tried a lot of things and read a lot of articles about that and somebody told me that is a 403 error. But I don’t know how to fix that.

How to use props in React

I am structuring my code for readability, and I want to use props for my data, but I am having trouble doing that.

Here is my code:

import React from 'react'
import { RxDotFilled } from "react-icons/rx";
import { MdHorizontalRule } from "react-icons/md";
import { ImStarEmpty } from "react-icons/im";
import { GrDocumentText } from "react-icons/gr";
import { FaShieldHalved } from "react-icons/fa6";
import { FaGift } from "react-icons/fa6";
import { FaRegMoneyBillAlt } from "react-icons/fa";
import { FaRegCalendarAlt } from "react-icons/fa";
import deal5 from "/src/assets/Deal-5.webp";
import deal4 from "/src/assets/Deal-4.webp";
import deal3 from "/src/assets/Deal-3.webp";
import deal2 from "/src/assets/Deal-2.webp";
import armchair from "/src/assets/Armchair.jpg"; 
import lector from "/src/assets/lector.webp";
import priodent from "/src/assets/Priodent.webp";
import Pariatur from "/src/assets/Pariatur.webp";
import Ninim from "/src/assets/Ninim.webp"
import Lommodo from "/src/assets/Lommodo.webp";
import banner6 from "/src/assets/banner6.jpg";
import star from "/src/assets/star.png";
import './Latest.css';


function Latest() {
  return (
  <>
        <div className='class-prod'>
            <p className='class-prod-par'>LATEST PRODUCTS</p>
            <span className='prod-span-one'></span>
            <RxDotFilled className='prod-dot'/>
        </div>
        <hr className='hr-rule' />
        
        <div className='prod-col'>
        <div className='prod-1'>
            <img src={deal5} alt="" />
            <div className="prod-1-txt">
                <p className='Balltip'>Balltip Nullaelit</p>
                <span className='star-icons'><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /></span>
                <p> <span className='prod-one-span'>$55.00</span> <span className='prod-two-span'>$65.00</span></p>

            </div>
        </div>


        <div className='prod-1'>
        <img src={deal4} alt="" />

            <div className="prod-1-txt">
                <p className='Balltip'>Censon Meatloa</p>
                <span className='star-icons'><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /></span>
                <p> <span className='prod-one-span'>$55.00</span> <span className='prod-two-span'>$65.00</span></p>

            </div>
        </div>


        <div className='prod-1'>
        <img src={deal3} alt="" />

            <div className="prod-1-txt">
                <p className='Balltip'>Sausage cowbee</p>
                <span className='star-icons'><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /></span>
                <p> <span className='prod-one-span'>$55.00</span> <span className='prod-two-span'>$65.00</span></p>

            </div>
        </div>



        <div className='prod-1'>
        <img src= {deal2} alt="" />

            <div className="prod-1-txt">
                <p className='Balltip'>Wamboudin Ribeye</p>
                <span className='star-icons'><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /><ImStarEmpty /></span>
                <p> <span className='prod-one-span'>$55.00</span> <span className='prod-two-span'>$65.00</span></p>

            </div>
        </div>

        <div className='second-sect'>
            
            <div className='doc-type'>
            <GrDocumentText className='doc-img' />
            <div className="doc-txt">
                <p className='doc-txt-par-1'>FREE DELIVERY</p>
                <p className='doc-txt-par-2'>On order over $49.86</p>
            </div>
        </div>
            <hr className='doc-hr'/>

        <div className='doc-type'>
            <FaShieldHalved  className='doc-img' />
            <div className="doc-txt">
                <p className='doc-txt-par-1'>ORDER PROTECTON</p>
                <p className='doc-txt-par-2'>Secured information</p>
            </div>
        </div>
        <hr className='doc-hr'/>


        <div className='doc-type'>
            <FaGift  className='doc-img' />
            <div className="doc-txt">
                <p className='doc-txt-par-1'>PROMOTION GIFT</p>
                <p className='doc-txt-par-2'>Special offers!</p>
            </div>
        </div>
        <hr className='doc-hr'/>


        <div className='doc-type'>
            <FaRegMoneyBillAlt className='doc-img' />
            <div className="doc-txt">
                <p className='doc-txt-par-1'>MONEY BACK</p>
                <p className='doc-txt-par-2'>return over 30 days</p>
            </div>
        </div>
        </div>
        

    </div>

    <div>
        <img src= {armchair} alt=""  className='armchair'/>
    </div>

    <div className="blog">
        <span className='class-prod-par-2'>LATEST BLOGS</span>
        <span className='blog-span'></span>
        <RxDotFilled className='prod-dot-2'/>
    </div>

    <div className="newsletter">
        <img src={lector} alt="" className='news-img' />

        <div className="newspaper-features">

         <p className='newsletter-txt'>Biten demons lector in vanderheit</p>
        <div className="newsletter-span-one">
        <FaRegCalendarAlt />
            <span>January 30th, 2024</span>
        </div>
        </div> 

    </div>

    <div className="top-rated">
        <p>TOP RATED</p>
        </div> <hr className='hr-rule' />

        <div className="top-rated-list">    
        <div className="top-rated-row">
            <img src={priodent} alt="" className='top-rated-img' />
            <div className="top-rated-col">
                <p className='top-rated-col-par'>Proident Laborum</p>

                <div className="star">
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                </div>

                <p className='top-rated-col-price'>$169.00</p>

            </div>
        </div>



        <div className="top-rated-row">
            <img src={Pariatur} alt="" className='top-rated-img' />
            <div className="top-rated-col">
                <p className='top-rated-col-par'>Pariatur Porking</p>

                <div className="star">
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src= {star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                </div>

                <p className='top-rated-col-price'>$98.00</p>

            </div>
        </div>


        <div className="top-rated-row">
            <img src={Ninim} alt="" className='top-rated-img' />
            <div className="top-rated-col">
                <p className='top-rated-col-par'>Ninim Spareri</p>

                <div className="star">
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                </div>

                <p className='top-rated-col-price'>$96.00</p>

            </div>
        </div>

        <div className="top-rated-row">
            <img src={Lommodo}alt="" className='top-rated-img' />
            <div className="top-rated-col">
                <p className='top-rated-col-par'>Lommodo Quitvena</p>

                <div className="star">
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                    <img src={star} alt="" className='top-rated-star'/>
                </div>

                <p className='top-rated-col-price'>$59.00</p>

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

        <img src= {banner6}
        alt="" 
        className='banner-6'
        />
    </>
    
  )
}

export default Latest

This is my App.jsx

import Trends from './MainSection/Trends.jsx';
import Login from './Login/Login.jsx';
import Register from './Login/Register.jsx';
import Layout from './MainSection/Layout.jsx';
import { createBrowserRouter, Outlet, RouterProvider } from "react-router-dom";


const router = createBrowserRouter([
  {
    path: "/",
    element: <Layout>
            <Outlet />

            </Layout>,
            

    children: [

       {
          path: "",
          element: <Trends />,
       },

       {
          path: "/register",
          element: <Register />,
        },

      {
        path: "/login",
        element: <Login />,

      },



      ]
            
  },
]);
        
    function App() {
      return <RouterProvider router={router} >
          {/* <div>
            <Home />
            <Register /> 
          </div>  */}
        </RouterProvider>
        
}
 

 export default App;
    
 

I have tried following some examples on the internet but I have not been able to accomplish it. I have tried creating a separate data.jsx file and importing it into my component, but still I feel i am doing something wrong.

Why do we get an uncaught error, when a promise is rejected before the rejection handler is locked in?

I am trying to catch the rejection reason of an already rejected promise, but I am getting an uncaught error.

I have spent some time studying promises, but still do not understand why the error occurs.

The purpose of this question is to understand the technical (ECMAScript spec) reason for why the uncaught error happens.

Consider the following code:

const getSlowPromise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Slow promise fulfillment value');
    }, 1000);
  });
};

const getFastPromise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('Fast promise rejection reason');
    }, 200);
  });
};

const slowP = getSlowPromise();
const fastP = getFastPromise();

slowP
  .then((v) => {
    console.log(v);
    console.dir(fastP);
    return fastP;
  }, null)
  .then(
    (v) => {
      console.log(v);
    },
    (err) => {
      console.log('Caught error >>> ', err);
    },
  );

In the above playground, the rejected promise is caught by the last then-handler (the rejection handler).

Inspecting the playground with DevTools will reveal that an error is thrown when fastP rejects. I am not sure why that is the case.

This is my current understanding of what is going on under the hood, in the JS engine:

  1. When the JS engine executes the script, it synchronously creates promise objects for each chained then(onFulfilled, onRejected). Let’s call the promises then-promises, with onFulfilled and onRejected then-handlers.
  2. The onFulfilled and onRejected then-handlers are saved in each then-promise’s internal [[PromiseFulfillReactions]] and [[PromiseRejectReactions]] slots. That still happens synchronously, without touching the macrotask or microtask queues
  3. When fastP rejects, reject('Fast promise rejection reason') is added to the macrotask queue, which is passed to the call stack once empty and executed (after global execution context has finished)
  4. When reject('Fast promise rejection reason') runs on the call stack, it will set fastP‘s internal [[PromiseState]] slot to rejected and the [[PromiseResult]] to 'Fast promise rejection reason'
  5. It will then add any onRejected handler it has saved in [[PromiseRejectReactions]] to the microtask queue, which will be passed to the call stack and executed once the call stack is empty
  6. Here is where I fall off. The then-promises we discussed previously do have handlers saved in their [[PromiseFulfillReactions]] and [[PromiseRejectReactions]] slots, as far as I understand. However, the first then-promise in the code snippet (created by the first then()) does not yet know that it should be locked in to the fastP promise, because that onFulfilled then-handler has not run yet (then-promise mirrors promise returned from the corresponding then-handler).

What am I missing?

changing the width of a div with setinterval

I have this code with css animation:

<div class="box">
  <div class="line"></div>
</div>

 <style>
@keyframes progress-bar {
  0% {
    width: 0;
  }

  50% {
    width: 100%;
  }

  100% {
    width: 0;
  }
}

  .box {
    position: relative;
    height: 3px;
    margin-top: 20px;
    background: transparent;
  }
  .line {
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 100%;
    background: red;
    -webkit-animation: progress-bar 6s ease-in infinite alternate forwards;
    animation: progress-bar 6s ease-in infinite alternate forwards;
  }
</style>

This is an example link to codesandbox: link

This allows me to fill in endlessly div.line in three seconds and then hide it’s width back in three seconds.

I want to implement in Vanila JS the same functionality with using setInterval. I understand that I need to use setInterval, loop and get the width using the clientwidth. But all my attempts either immediately clear setInterval or doesn’t work.
Please help me find the optimal solution, thank you.

tree-sitter-typescript not working with my tree-sitter library in javascript

I have been trying to get tree-sitter-typescript to work in javascript but i’s not working always throwing the error Invalid language object but tree-sitter works well with tree-sitter-javascript and tree-sitter-python. here’s my code :

const path = require('path');
const Parser  = require('tree-sitter');
const Typescript= require('tree-sitter-typescript').typescript;

const parser= new Parser();
parser.setLanguage(Typescript);

WordPress Gutenberg Custom Block Issues

import { registerBlockType } from "@wordpress/blocks";
import { useSelect } from "@wordpress/data";
import { useState } from "@wordpress/element";
import { Button, TextControl } from "@wordpress/components";

const dummyData = [
    { id: 1, title: "Term 1", excerpt: "Description of Term 1" },
    { id: 2, title: "Term 2", excerpt: "Description of Term 2" },
    { id: 3, title: "Term 3", excerpt: "Description of Term 3" },
    // Add more dummy data as needed
];

registerBlockType("custom-blocks/medical-terms", {
    title: "Medical Terms",
    category: "widgets",
    edit: () => {
        const [search, setSearch] = useState("");
        // Use dummyData directly instead of fetching from WordPress
        const terms = dummyData.filter((term) =>
            term.title.toLowerCase().includes(search.toLowerCase()),
        );

        return /*#__PURE__*/ React.createElement(
            "div",
            null,
            /*#__PURE__*/ React.createElement(TextControl, {
                label: "Search",
                value: search,
                onChange: setSearch,
            }),
            /*#__PURE__*/ React.createElement(
                "div",
                null,
                /*#__PURE__*/ React.createElement(Button, null, "All"),
                [...Array(26)].map((_, index) =>
                    /*#__PURE__*/ React.createElement(
                        Button,
                        {
                            key: index,
                            onClick: () => setSearch(String.fromCharCode(65 + index)),
                        },
                        String.fromCharCode(65 + index),
                    ),
                ),
            ),
            /*#__PURE__*/ React.createElement(
                "ul",
                null,
                terms.map((term) =>
                    /*#__PURE__*/ React.createElement(
                        "li",
                        {
                            key: term.id,
                        },
                        /*#__PURE__*/ React.createElement("h3", null, term.title),
                        /*#__PURE__*/ React.createElement("div", {
                            dangerouslySetInnerHTML: {
                                __html: term.excerpt,
                            },
                        }),
                    ),
                ),
            ),
        );
    },
    save: () => null,
});

enter image description here

enter image description here

I’ve developed a custom WordPress block for displaying medical terms. The block functions perfectly in the editor page, allowing users to search for terms and displaying the results accordingly. However, when I view the page on the frontend where the block should be displayed, it doesn’t appear.

Request for Assistance:

I’m seeking assistance to troubleshoot why my custom WordPress block isn’t displaying on the frontend despite functioning correctly in the editor. Any insights, suggestions, or further troubleshooting steps would be greatly appreciated.

Thank you in advance for your help!

How to drop retried events after x minutes in Firebase Functions 2nd gen

I am migrating some Firebase Functions code from 1st to 2nd gen. In my 1st gen functions I am using a shouldDropEvent helper which looks at the timestamp of the context and decides to drop the event after it has been retried for x minutes.

For 2nd gen I do not know where to find this timestamp.

Also, I would like to configure the retry behaviour, but I don’t think it’s possible with the current API.

The pubSendNotificationToUserToken is an abstraction I use for pubsub that keeps the topic and handler colocated in one place. Please ignore it.

import { pubSendNotificationToUserToken } from "@repo/core/notifications";
import type { EventContext } from "firebase-functions";
import functions from "firebase-functions";
import { onMessagePublished } from "firebase-functions/v2/pubsub";

const MINUTE_MS = 60 * 1000;
export const retryEventMaxAgeMs = 20 * MINUTE_MS;

export const sendNotificationToUserToken_1stGen = functions
  .runWith({
    failurePolicy: true,
  })
  .pubsub.topic(pubSendNotificationToUserToken.topic)
  .onPublish(async (message, context) => {
    if (shouldDropEvent(context, MINUTE_MS * 5)) {
      return;
    }

    await pubSendNotificationToUserToken.handle(message.json);
  });

export const sendNotificationToUserToken_2ndGen = onMessagePublished(
  {
    topic: pubSendNotificationToUserToken.topic,
    retry: true,
  },
  async (event) => {
    await pubSendNotificationToUserToken.handle(event.data.message.json);
  }
);

/**
 * Check if max age has been reached. Timestamp should be in RFC 3339 format to
 * match cloud functions context event timestamp.
 */
function shouldDropEvent(
  context: EventContext<unknown>,
  maxAgeMs = retryEventMaxAgeMs
) {
  const eventAge = Date.now() - Date.parse(context.timestamp);

  if (eventAge > maxAgeMs) {
    console.error(
      new Error(
        `Dropping event ${context.eventType} for ${context.resource.name} because max age was reached.`
      )
    );
    return true;
  }

  return false;
}

Determining a click region for scroll, simulating the click

Microsoft’s OneDrive website has many pages where the scroll bar doesn’t work with page up/down keys when the page loads: you have to click a region of the page near the scroll bar, then keys start working. (Happens with the landing page, the “On This Day” page, etc.)

I want to write a tampermonkey script that does this click when the page loads. I’ve poked around in DevTools for quite some time trying to figure out what happens/changes when I make this click, and I’m at a loss.

How do I go about watching this work in DevTools? Which view reveals it? Should I be using a different tool? Are there js commands I can run from the console that help me out here?

I’m using the latest Google Chrome browser.

(MRE unavailable for obvious reasons.)

showing [Object: null prototype] {} in req.cookies

I am trying to store cookie and get via cookie-parser, but only showing [Object: null prototype] {}
I am using postman to check, also using cores and body-parser

This is my index.js

const dotenv = require("dotenv");
const express = require("express");
const connectDB = require("./config");
const bodyParser = require("body-parser");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const errorHandler = require("./middlewares/errorHandler");
const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true,
};

dotenv.config();
connectDB();

const app = express();

app.use(bodyParser.urlencoded({ extended: true, limit: "30mb" }));

app.use(bodyParser.json());

app.use(cookieParser());
app.use(cors(corsOptions));

app.use("/v1/user", require("./routes/userRouter"));

app.use(errorHandler);
const PORT = process.env.PORT || 8000;
const server = app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

This is my user controller

login: async (req, res) => {
    try {
      const { email, password } = req.body;
      if (!email || !password)
        return res.status(400).json({ msg: "Please fill all the fields." });

      if (!validateEmail(email))
        return res
          .status(400)
          .json({ msg: "Please enter valid email address." });

      const user = await User.findOne({ email }).select("+password");
      if (!user)
        return res.status(400).json({ msg: "This email does not exist." });

      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch)
        return res.status(400).json({ msg: "Password is incorrect." });
      console.log(isMatch);

      const refresh_token = createRefreshToken({ id: user._id });
      res.cookie("refreshtoken", refresh_token, {
        httpOnly: true,
        path: "/user/refresh_token",
        maxAge: 7 * 24 * 60 * 60 * 1000,
      });
      res.json({ msg: "Login success!" });
    } catch (error) {
      return res.status(500).json({ msg: error.message });
    }
  },
  getAccessToken: async (req, res) => {
    try {
      const rf_token = req.cookies.refreshtoken;
      console.log(req.cookies);
      if (!rf_token) return res.status(400).json({ msg: "Please login now!" });

      jwt.verify(rf_token, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
        if (err) return res.status(400).json({ msg: "Please login now!" });
        const access_token = createAccessToken({ id: user.id });
        res.json({ access_token });
      });
    } catch (error) {
      return res.status(500).json({ msg: error.message });
    }
  },

In getAccessToken showing [Object: null prototype] {}

This is my package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.20.2",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "express-async-handler": "^1.2.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.3.2",
    "nodemailer": "^6.9.13"
  },
  "devDependencies": {
    "nodemon": "^3.1.0"
  }
}

I am stuck in getting cookies value, please help

I have a problem when I host my backend to the Render

I use multer.diskStorage to store my upload image. It is fine befor hosted on Render. It have problem when i host to the render. The image are not appear when to call the api . Some object are appear like id , category and description . But image are not apper.There is my code

const storage = multer.diskStorage({
    destination: path.join(__dirname, 'upload', 'images'), // Set the destination path outside the src folder
    filename: (req, file, cb) => {
        cb(null, `${Date.now()}${path.extname(file.originalname)}`);
    }
});

const upload = multer({ storage: storage });

//Creating Upload Endpoint for image
app.use('/images', express.static(path.join(__dirname, 'upload', 'images')));

// Update the upload endpoint to return the full image URL
app.post("/upload", upload.single("product"), (req, res) => {
    res.json({
        success: 1,
        image_url: `http://${req.hostname}:${port}/images/${req.file.filename}` // Dynamically generate image URL
    });
});```


> I want to image apper , when i hosted on Render :))