“Http failure during parsing” NodeJS + Angular + CPanel

Service:

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

constructor(
    private http: HttpClient
) { }

private API_GET_BARCO_BY_CANTIDAD = `${GlobalVariables.URL_NODE}/barco/encontrar/c/?barcosC=`;

private header = new HttpHeaders({
    'Content-Type': 'application/json'
});

public getBarcoByC(cantidad: Number): Observable<any> {
    return this.http.get<any>(this.API_GET_BARCO_BY_CANTIDAD + cantidad, { headers: this.header });
}

API:

const router = Router();
const Barco = require('../models/Barco')

router.get("/barco/encontrar/c/", getBarcosByC);

async function getBarcoBy(req, res) {
  try {
    let id = req.params.id;
    const barco = await Barco.findById(id, function (err, docs) {
      if (err) {
        console.log(`n[BarcosApi Error] Found Barco By Id(${id}):n`,err)
      } else {
        console.log(`n[BarcosApi] Found Barco By Id(${id}):n`, docs)
      }
    }).clone().catch(function (err) { console.log(err) })

    if ('err' in barco) return res.status(barco.codestatus).json(barco.err);
    return res.status(200).json(barco);
    
  } catch (err) {
    console.log("[BarcosApi] getBarcoByError", err);
  }
}

Console: temp0.error.text
Gives back the whole index.html page as error.text

All GET requests have the same respond(index.html), while POST, UPDATE, DELETE works flawlessly

How to mock Node’s worker_thread in Jest?

I have a worker_thread like this:

const worker = new Worker(path.resolve(__dirname, "worker.mjs"))
  .on("message", (data) => {
    this.date = data;
  });

Inside that worker.mjs, I run a REST API GET request, and some other formatting logic on the data retrieved.

and I want to mock it in Jest, I tried:

import path from "path";
import { MyModule } from "./MyModule";

describe("MyModule", () => {
  jest.mock(path.resolve(__dirname, "worker.mjs"));

  it("1st spec", () => {
    expect(1+1).toEqual(2)
  });
});

But when I run the test, jest doesn’t mock the worker, jest goes inside the worker code and actually executes the API call.

What is missing?

CSS HTML TABLE Row Drop Down Hidden

This should seem simpler. But I can’t find resolve online.

Just trying to have a new drop down row to enter some data on a form.
Should be simple. But the drop down shows in the first cell only.
Even when using colspan=5.

Or is there a better way? Thx for any help.

      <table cellspacing=0 cellpadding=7 border=1>
      <tr bgcolor=#efefef>
      <td></td>
      <td>Date</td>
      <td>DATA</td>
      <td>MORE DATA</td>
      <td>Method</td>
      </tr>
      <tr>
      <td>
      <button onclick="javascript:showElement('abcdata')" style="padding:4px" class=verd8> SHOW NEW ROW </button>
      </td>
      <td>Jan 22, 2022</td>
      <td>SOME DATA</td>
      <td>SOME MORE</td>
      <td>BUTTONDROP</td>
      </tr>
      <tr id="abcdata" style="display:none;"> 
      <td colspan=5>
      SHOW NEW ROW ACROSS ALL CELLS : sfdgsdfgs hlahhfa la dfl dfljhsd flhsd flhsdf lhdsfh asf alhd a</td>
      </tr>
      </table>

how to show posts by sub-categorys in react by json data?

I wanna make sub-categories and show the posts by these sub-categories. I follow this project to make it but here are one list category I need more categories like this which are nested by the first category as I want. I have some changes to the App.js file but I am not able to fix it.
When I create a sub-category in the JSON file does not show the category name and post details also. how to do it plz help me if you want.

This is the main project GitHub link

** Here My Changes Codes :**

App.js

import React, { useState } from "react";
import Data from "./Data";
import Card from "./Card";
import Buttons from "./Buttons";

const App = () => {
  const [item, setItem] = useState(Data);

  const menuItems = [
    ...new Set(Data.category?.map((Val) => Val.category.subcategory)),
  ];

  const filterItem = (curcat) => {
    const newItem = Data.category.filter((newVal) => {
      return newVal.category.subcategory === curcat;
    });
    setItem(newItem);
  };
  return (
    <>
      <div className="container-fluid">
        <div className="row">
          <h1 className="col-12 text-center my-3 fw-bold">
            Food Filtering App
          </h1>
          <Buttons
            filterItem={filterItem}
            setItem={setItem}
            menuItems={menuItems}
          />
          <Card item={item} />
        </div>
      </div>
    </>
  );
};

export default App;

Button.js

import React from "react";
import Data from "./Data";

const Buttons = ({ filterItem, setItem, menuItems }) => {
  return (
    <>
      <div className="d-flex justify-content-center">
        {menuItems.map((Val, id) => {
          return (
            <button
              className="btn-dark text-white p-1 px-2 mx-5 btn fw-bold"
              onClick={() => filterItem(Val)}
              key={id}
            >
              {Val}
            </button>
          );
        })}
        <button
          className="btn-dark text-white p-1 px-3 mx-5 fw-bold btn"
          onClick={() => setItem(Data)}
        >
          All
        </button>
      </div>
    </>
  );
};

export default Buttons;

Card.js

import React from "react";

const Card = ({ item }) => {
  return (
    <>
      <div className="container-fluid">
        <div className="row justify-content-center">
          {item.map((Val) => {
            return (
              <div
                className="col-md-4 col-sm-6 card my-3 py-3 border-0"
                key={Val.id}
              >
                <div className="card-img-top text-center">
                  <img src={Val.subimg} alt={Val.subtitle} className="photo w-75" />
                </div>
                <div className="card-body">
                  <div className="card-title fw-bold fs-4">
                    {Val.subtitle} &nbsp;&nbsp;&nbsp;&nbsp;--&nbsp;&nbsp;
                    {Val.subprice}
                  </div>
                  <div className="card-text">{Val.subdesc}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

export default Card;

Data.js

const Data = [
  {
    id: "1",
    title: "Poha",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://c.ndtvimg.com/2021-08/loudr2go_aloo-poha_625x300_05_August_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
    desc: " Poha. Light, filling and easy to make, poha is one famous breakfast that is eaten almost everywhere in the country. And the best part is- it can be made in a number of ways. Kanda poha, soya poha, Indori poha, Nagpur Tari Poha are a few examples",
  },
  {
    id: "2",
    title: "Upma",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
    desc: " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
  },
  {
    id: "3",
    title: "Cheela",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://c.ndtvimg.com/2019-05/1afu8vt8_weight-loss-friendly-breakfast-paneer-besan-chilla_625x300_25_May_19.jpg?im=FaceCrop,algorithm=dnn,width=620,height=350",
    desc: "A staple across Indian households, moong dal is widely used in a number of Indian delicacies. One such delicacy is moong dal cheela. You can also add paneer to this recipe to amp up the nutritional value and make it, even more, protein-dense",
  },
  {
    id: "4",
    title: "Channa Kulcha",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-04/chana-kulcha_625x350_41429707001.jpg",
    desc: "A classic dish that never goes out of style. The quintessential chana kulcha  needs only a few ingredients - cumin powder, ginger, coriander powder, carom powder and some mango powder, which is what gives the chana it's sour and tangy taste.",
  },
  {
    id: "5",
    title: "Egg Curry",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2017-11/goan-egg-curry_620x350_41511515276.jpg",
    desc: "Eggs are a versatile food that can be cooked for any meal of the day. From breakfast to dinner, it can be a go-to food. Here is a mildly-spiced egg curry made with garlic, onions, a whole lot of kasuri methi, fresh cream, yogurt and fresh coriander.",
  },
  {
    id: "6",
    title: "Paneer Aachari",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-04/paneer_625x350_61429707960.jpg",
    desc: "Don't get intimidated by the list of ingredients because not only are already in your kitchen cabinet, but also because all they'll need is 20 minutes of your time. Chunks of cottage cheese cooked in some exciting spices, yogurt and a pinch of sugar.",
  },
  {
    id: "7",
    title: "Fish Fry",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-06/indian-dinner_625x350_41434360207.jpg",
    desc: "Get your daily dose of perfect protein. Pieces of surmai fish marinated in garlic, cumin, fennel, curry leaves and tomatoes are pan-fried in refined oil and served hot. This fish fry recipe has a host of delectable spices used for marination giving it a unique touch.",
  },
  {
    id: "8",
    title: "Dum Alloo",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-06/indian-dinner_625x350_51434362664.jpg",
    desc: "Your family will thank you for this absolutely fantastic bowl of dum aloo cooked Lakhnawi style. Take some potatoes, crumbled paneer, kasuri methi, butter, onions and some ghee.",
  },
  {
    id: "9",
    title: "Malai Kofta",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2017-10/makhmali-kofte_620x350_51508918483.jpg",
    desc: "A rich gravy made of khus khus, coconut and milk that tastes best with koftas made from khoya. This velvety and creamy recipe will leave you licking your fingers. Makhmali kofte can be your go-to dish for dinner parties as this is quite different from other kofta recipes and extremely delicious.",
  },
  {
    id: "10",
    title: "Malai Kofta",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2017-10/makhmali-kofte_620x350_51508918483.jpg",
    desc: "A rich gravy made of khus khus, coconut and milk that tastes best with koftas made from khoya. This velvety and creamy recipe will leave you licking your fingers. Makhmali kofte can be your go-to dish for dinner parties as this is quite different from other kofta recipes and extremely delicious.",
  },
];

export default Data;

How to target a div using content inside the div

I have 2 divs with same class name but different strings inside the div. I want to use an insertAfter the first div to display some additional text, but the text is being displayed under both divs:

<div class='test'>First Div</div>
<div class='test'>Second Div</div >

My approach:


if(document.getElementsByClassName('test')[0] && document.getElementsByClassName('test')[0].inner
HTML == 'First Div') {
          $('<h2>Inserting New Text</h2>').insertAfter('.test')[0];
                     }

But this adds the text after both the First Div and the Second Div. I want to know if there is a way to insert only once or insert after matching the string

PDFkit (Node): How to create paragraph indents?

I’m trying to create paragraph indents in PDFkit. The PDFkit docs state that the indent attribute is “to indent each paragraph of text”. While trying this, only the first line has an indent.

const doc = new PDFDocument({ size: "A4" });
doc.pipe(fs.createWriteStream('output2.pdf'));
doc.addPage()
doc.text('fdgfdgfg fggfdgfdg fgfdg fdg dfgdfgdfg dfgfdg fgfgfdg fdgdfgdfg', { indent: 30 })
doc.end();

The code delivers an indent only in the first line of the paragraph. How can I indent the whole paragraph?

Error in my command line when i tried to run my node app.js

When i tried to run node app.js from my server. It brought the error below:

C:UsersBLUE HOSTDesktoptodolist-v1>node app.js
C:UsersBLUE HOSTDesktoptodolist-v1node_modulesexpresslibrouterindex.js:464
throw new TypeError(‘Router.use() requires a middleware function but got a ‘ + gettype(fn))
^

TypeError: Router.use() requires a middleware function but got a string
at Function.use (C:UsersBLUE HOSTDesktoptodolist-v1node_modulesexpresslibrouterindex.js:464:13)
at Function. (C:UsersBLUE HOSTDesktoptodolist-v1node_modulesexpresslibapplication.js:220:21)
at Array.forEach ()
at Function.use (C:UsersBLUE HOSTDesktoptodolist-v1node_modulesexpresslibapplication.js:217:7)
at Object. (C:UsersBLUE HOSTDesktoptodolist-v1app.js:6:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)

This is my app.js file:

const express = require("express");
const app = express();
app.use(express.urlencoded({extended: true}));
app.use("view engine", "ejs");

app.get("/",function(req,res) {
var today = new Date();
var currentDay = today.getDay();
var day = "";

if (currentDay === 6 || currentDay === 0) {
day = "weekend";
} else{
day = "weekday";
 }
 res.render("list", { kindOfDay: day });
});

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

This is my list.ejs file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To do List</title>
</head>
<body>
<h1><%= kindOfDay %></h1>
</body>

Change outer ul background color when inner li has a class=”selected”

i have some menus with unordered list (ul)

<ul class="myul">
<li>Button1</li>
<li>Button2</li>
<li class="selected">Button3</li>
<li>Button4</li></ul>

<ul class="myul">
<li>Button5</li>
<li>Button6</li>
<li>Button7</li>
<li>Button8</li></ul>
and so on...

how i can change with jQuery the background color of outer “ul” when the inner “li” has class=”selected”?

thanks in advance.

Can’t call function within keyDown or keyPress event handlers

Can’t call function within keyDown or keyPress event handlers.

 var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];

$(document).on("keydown",  nextSequence);

function nextSequence() {
   var randomNum = Math.floor(Math.random() * 4);
   var randomChosenColor = buttonColors[randomNum];
   return gamePattern.push(randomChosenColor);
}

How to Optimize Subquery in Objection JS?

I want to optimise my subquery. From the mysql doc i found.

> SELECT * FROM t1 WHERE t1.column1 IN   (SELECT column1 FROM t2 ORDER
> BY column1); SELECT * FROM t1 WHERE t1.column1 IN   (SELECT DISTINCT
> column1 FROM t2); SELECT * FROM t1 WHERE EXISTS   (SELECT * FROM t2
> LIMIT 1);

I was able to achieve this format using this objection js code.

Person.query()
  .from(
    Person.query()
      .select(
        'persons.name as persons_name',
        'persons.disclaimer as persons_disclaimer',
        'persons.id as persons_id'
      )
      .as('optimised')
      .limit(40)
  )
  .select('optimised.*')
  .select((qb) => {
    qb.select(raw(`sum(act.count)`))
      .from('activity as act')
      .where('act.p_id', '=', 'optimised.persons_id')
      .as('actCountSum');
  })
  .select((qb) => {
    qb.select(raw(`count(*)`))
      .from('activity as act')
      .where('act.p_id', '=', 'optimised.persons_id')
      .as('actCount');
  })
  .debug();

But the problem is i am getting null and 0 respectively because on where clause its passing optimised.persons_id as a string.

Any solution?

Click Instantly Triggers Event Listener That Is Created By The Click

I have a button with an event listener. When somebody clicks it, all content on my webpage gets replaced with something else, and a new event listener is put on the whole body of the page. However, clicking the button instantly triggers the new event listener that is only created after clicking it. Of course clicking the button also means that you clicked the body, but the new event listener is only created through the click, so I thought it wouldn’t instantly trigger. I don’t understand why that’s happening or how to prevent it. I hope my question isn’t too stupid. I’m pretty new to this whole thing and trying to teach myself the basics.

Edited to make my point clearer.

Is there a way to send 2 requests with a delay inbetween them without the user actively staying on the webpage

I’ll explain the question a bit clearer here.

So I have a button that sends a request through php when pressed. This request grants the user access to a Demo version of my service indefinitely. Is there a way to send a separate request 60 minutes later which is intended to expire their demo.

Could I simply create a php function that has a delay? Or would the user have to stay on the webpage in order for it to complete the function. Or is there another way to complete this that I’m not thinking of.

Thanks
-Andrew.