Angular/Typescript: How to get details about unsuccessful http request? (connection refused, CORS, …)

Everytime a http requests fails in my Angular project (e.g. ‘service not available’ or ‘CORS policy’) I’m receiving a HttpErrorResponse with { status: 0, statusText: 'Unknown Error', ...}
But I would like to get more details to give additional information to the user.

When inspecting the developer console of the browser I see some more information like net::ERR_CONNECTION_REFUSED (service unavailable) and net::ERR_FAILED (CORS policy). But I have no idea how to get access to this information within my code.

console output of the browser in case the service is down
console output of the browser in case the service is down

console output of the browser in case the CORS policy blocks the request
console output of the browser in case the CORS policy blocks the request

I tried to get the information in this way

    try {
      this.http.get<MyResponseType[]>(`${this.HOST}/path/to/resource?param=${param}`)
      .pipe(
        catchError((err) => of(`I caught: ${err.message}`))
      ).subscribe(
        (config) => console.log(config)
      );
    } catch (e:any) {
      console.log("exception was thrown");
      console.warn(e);
    }

Everything I got was HttpErrorResponse with { status: 0, statusText: 'Unknown Error', ...}.
Has anyone an idea how to get more details?

To be clear: I’m not interested in how to solve the problems shown in the screenshots. I want to know how to handle the errors in a better way.

Thanks a lot!

Why does my code in ReactJS with fabricjs render a transparent object instead of an image clipped into a path object?

I’m using ReactJS with fabric to render an image clipped into a path object on a canvas element. However, for some reason, my code is rendering a transparent object instead of the image I want. I’ve tried using the globalCompositeOperation property, as well as setTimeout, but nothing seems to be working.

Part of code that should render pathObject and upload Image

useEffect (() => {
  if (canvas) {
    // Create a black rectangle from an SVG path
    const pathObject = new fabric.Path('M 96.4745 152.7105 C 83.8745 74.9105 159.391 52.4605 198.7245 50.9605 C 198.7245 27.9603 219.2245 7.7104 249.9745 2.4603 C 291.2245 -8.5397 313.2245 29.9603 313.2245 38.4603 C 329.6245 44.6603 362.0575 41.0436 376.2245 38.4603 C 393.3075 29.9603 434.5745 25.1603 462.9745 73.9605 C 498.4745 134.9605 439.9745 167.9605 433.4745 172.4605 C 440.2245 171.2105 459.7245 192.2105 455.7245 200.2105 C 480.7245 198.4605 541.725 204.7105 543.725 242.7105 C 546.925 306.7105 501.725 315.877 478.7245 312.4605 C 482.2245 317.0435 488.8245 330.5605 487.2245 347.9605 C 508.225 412.4605 471.4745 431.9605 451.7245 439.9605 C 449.7245 462.4605 438.7245 474.7105 412.9745 491.7105 C 393.2245 538.21 357.2245 535.21 313.2245 529.21 C 259.9745 549.71 232.9745 531.71 219.2245 521.96 C 194.2245 519.96 184.9745 508.71 174.4745 497.7105 C 108.6745 515.71 79.2245 479.377 72.7245 458.9605 H 49.7244 C 35.9744 459.627 7.0244 449.3605 1.2243 402.9605 C 10.4743 348.2105 43.7244 349.9605 60.9745 347.9605 C 36.3743 324.9605 43.2244 290.2105 49.7244 275.7105 C 29.141 275.7105 -4.8911 244.2105 1.2243 217.2105 C 14.4743 158.7105 45.7244 158.7105 96.4745 152.7105 Z', {
      fill: 'black',
      left: canvas.width / 1.5,
      top: canvas.height / 2,
      selectable: false,
      stroke: 'blue',
      strokeWidth: 5,
    });
    pathObject.set({
      originX: 'center',
      originY: 'center',
    })

    // Add the rectangle to the canvas
    canvas.add(pathObject);

    setPathObject(pathObject);
  }
}, [canvas])

// Upload plików  
const handleFileUpload = (e) => {
const file = e.target.files[0];
  // Pogorszenie jakości przed dodaniem
  new Compressor(file, {
  quality: 0.6,
  maxWidth: 800,
  maxHeight: 800,
  success(result) {
    // Dodanie do płótna
    const reader = new FileReader();
    reader.readAsDataURL(result);
    reader.onload = (e) => {
    const image = new Image();
    image.src = e.target.result;
    image.onload = () => {

    // Stworzenie obrazka i dodanie go jako dziecko kwadratu
    const img = new fabric.Image(image, {
      left: canvas.width - 600,
      top: 100,
      scaleX: pathObject.width / image.width,
      scaleY: pathObject.height / image.height,
      selectable: true,
      lockScalingX: true,
      lockScalingY: true,
      lockRotation: true,
      clipPath: pathObject,
    });

    // Dodanie wszystkiego do płótna
    canvas.add(img).renderAll();

        };
      };
    },
  error(err) {
  console.log(err.message);
  },
  });
};

How to crop an image from canvas context.drawImage in HTML from getUserMedia API

I’m trying to crop an image that I draw with canvas that I capture from a tag, which I input from a webcam stream. The crop area should correspond to another div’s position and length/width that is also on the screen. I’ve tried using clientWidth, offsets, and different paramters with no success. I know this is likely a CSS issue and understanding how to calculate offsets from the window and the element with javascript.

I”m on an old computer and there are no tooltips for the symbols in this editor, can’t figure out which one is the code block, i’ve posted the code here:
https://zov2.pythonanywhere.com/1/27/simple-crop

How to get how many characters are in multiple strings

I have this situation where I have to get or calculate how many characters are in multiple strings. Example:



var aText = Array(

      "There are only 2 types of people in the world:",

      "Girls and boys, any other thing? i don't know.");

There’s more than 80 characters in both strings combined. Another note is that, the strings may not be fixed as they may increase or decrease. Is there a way I can do this in JavaScript?

I tried using aText.length but this only returned how many strings where in the variable. Which in this case is only 2.

Formik Default Values UseEffect Hook Does Not Load

I am trying to set the initial values of a form in React.JS in the useEffect hook. The memo field fails to load any data. What is wrong with my code?

 
     const [initialValues, setInitialValues] = useState<PurchaseOrderDto>();

 useEffect(() => {

        agent.PurchaseOrder.List(id).then((response) => {
            setInitialValues(response.data);
        });

}, []);
return (
        <Formik
            enableReinitialize
            initialValues={ initialValues }
            onSubmit={async (values, { setErrors, setStatus, setSubmitting }) => {
                try {
                    
                } catch (error: any) {
                    const message = error.message || "Something went wrong";

                    setStatus({ success: false });
                    setErrors({ submit: message });
                    setSubmitting(false);
                }
            }}
        >
            {({
                errors,
                handleBlur,
                handleChange,
                handleSubmit,
                isSubmitting,
                touched,
                values,
            }) => (
                <form noValidate onSubmit={handleSubmit}>
                    {errors.submit && (
                        <Alert mt={2} mb={1} severity="warning">
                            {errors.submit}
                        </Alert>
                    )}

                    <TextField
                        type="text"
                        name="Memo"
                        label="Memo"
                        value={initialValues?.memo}
                        //error={Boolean(touched.Memo && errors.Memo)}
                        fullWidth
                        helperText={values?.memo && errors.memo}
                        onBlur={handleBlur}
                        onChange={handleChange}
                        my={3}
                    />

Javascript – adding listeners to dynamically created HTML elements works from console, but not directly from code? [duplicate]

I often create modal content elements dynamically by inserting strings into the modal element’s innerHTML. In the strings, I include class attributes to later access the elements using doc.qSelAll later like:

someData.forEach(item=>{
modal.innerHTML += `<span id='${item.label' class='modalspan'> /*sth*/ </span><br>`;
});
document.querySelectorAll('.modalspan').forEach(span=>{ console.log(span); span.addEventListener(/* sth */); });

This logs the span elements, indicating they’ve been inserted into the DOM, but the eventListeners won’t start working. However, when I write literally the same code into the console directly, the listeners DO work. It doesn’t make much sense at all so I wonder why this is.

I tried attaching the listeners later in a separate function using setTimeout, so that the html elements had time to load correctly, but that didn’t help either.

Disclaimer: I do not like to use document.createElement and then .appendChild, because it messes things up (you can’t add line breaks so precisely and the code gets a lot longer). I think it wouldn’t solve the problem either, anyway.

Configure custom scrolling behavior for Jupyterlab using Stylus, based on cell output length and type

This question is a followup question to this thread : Jupyterlab active scroll bars for long results

In a notebook opened with Jupyterlab, when faced with cell outputs of different types (plots / text), and different lengths, it would be interesting to have a different scrolling behavior for each cell based on conditions checking those cells.

In my case I would like to have no scrolling when the output contains plots and when the output is less then 50 lines, but then activate scrolling and a smaller cell height when these conditions are met.

As the question mentioned before proposes the use of the browser extension Stylus which is based on CSS, is there a way to modify this Stylus configuration file to include this custom behavior ?

.jp-OutputArea-child {
    max-height: 33em;
}

.jp-OutputArea-child .jp-OutputArea-output {
    overflow: auto;
}

My experience in CSS being very limited, the idea would be (in pseudo-code):

IF OutputArea.height >= 50 AND OutputArea.hasPlot == False: 
{
  .jp-OutputArea-child {
      max-height: 33em;
  }
  .jp-OutputArea-child .jp-OutputArea-output {
      overflow: auto;
  }
}

ELIF OutputArea.hasPlot == True: 
{
  .jp-OutputArea-child {
      max-height: None; 
  }
  .jp-OutputArea-child .jp-OutputArea-output {
      overflow: disabled; 
  }
}

ELIF OutputArea.height < 50 AND OutputArea.hasPlot == False: 
{
  .jp-OutputArea-child {
      max-height: None;
  }
  .jp-OutputArea-child .jp-OutputArea-output {
      overflow: disabled;
  }
}

Of course I don’t expect any checks to be of this type, and the checks may differ based on the plot type (matplotlib/plotly/openturns), even if for now matplotlib checks would be sufficient.

Also Stylus seems to be expendable using javascript, but my knowledge there has the same limitations. And as it seems that CSS cannot handle exceptions this custom behavior might have to pass over a style.js file.

Is there a jupyterlab setting or extension that already implements those behaviors, could the Stylus configuration file include these conditions, or is the only way to use a custom javascript extension?

TextDecoder with latin1 encoding is giving different result from String.charCodeAt

I want to understand what is causing the difference. I have a list of the first 256 codes.

const codes = new Array(256).fill(0).map((_,i) => i); //[0, 1, 2, 3, ..., 255]
const chars1 = new TextDecoder('latin1').decode(new Uint8Array(codes));

This gives the following string:

'x00x01x02x03x04x05x06x07btnvfrx0Ex0Fx10x11x12x13x14x15x16x17x18x19x1Ax1Bx1Cx1Dx1Ex1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~x7F€x81‚ƒ„…†‡ˆ‰Š‹Œx8DŽx8Fx90‘’“”•–—˜™š›œx9DžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'
const chars2 = String.fromCharCode(...codes);

This gives the following string:

'x00x01x02x03x04x05x06x07btnvfrx0Ex0Fx10x11x12x13x14x15x16x17x18x19x1Ax1Bx1Cx1Dx1Ex1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~x7Fx80x81x82x83x84x85x86x87x88x89x8Ax8Bx8Cx8Dx8Ex8Fx90x91x92x93x94x95x96x97x98x99x9Ax9Bx9Cx9Dx9Ex9F ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'
console.log(chars1 === chars2) //prints false

In order to check what index/code is causing the difference, I used the following function:

function findDiff(str1,str2) {
    const diff = [];
    for(let i=0;i<str1.length;i++) {
        if(str1.charAt(i) !== str2.charAt(i)) {
            diff.push(i);
        }
    }
    return diff;
}

findDiff(chars1, chars2); // [128, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159]

Why do these code points generate a different character when using TextDecoder and String.fromCharCode ?

I was expecting both methods to give the same string output with the first 256 code points.

The problem of changing the tippy text via jq

Sorry to bother you. I use Tippy.js v6.3.7 and there was a problem
There is a “div” element with “data-tippy-content=”Save””. By means of JQ, I change to the text “Delete”, but when hovering, the hints are covered on top of each other. I need only a new “Delete” label to appear. Please help me to sort out the problem, all cookies

        $.each(array, function(index, val) {
            var element_ = '.js-btn[data-id="' + val +'"]';
            $(element_).removeAttr("data-tippy-content");
            tippy(element_, {
                content: 'Delete',
            });
        });

I don’t even know what to do. I’ve been sitting and thinking for an hour

Evaulate Javasript keyword error – RobotFramework -browser

I am getting error , when I am running Evaluate Javascript keyword in a RF browser library,
when I am running very same script in browser console, it works fine.
I also did try without semicolon at the end of line but didnt work neither , with another error
could anyone help? what I am doing wrong

Evaluate JavaScript    document.getElementsByClassName("dz-hidden-input")[0].style.visibility='visible';
Error: locator.evaluate: Unsupported token ";" while parsing selector "document.getElementsByClassName("dz-hidden-input")[0].style.visibility='visible';"
=========================== logs ===========================
waiting for selector "document.getElementsByClassName("dz-hidden-input")[0].style.visibility='visible';"

this element is set to hidden initially and in order to upload attachment I need to make it visible first, that what I am about to achieve

What am I doing wrong? Uncaught ReferenceError: exports is not defined [duplicate]

I am just trying to create a simple Promise following Typscript principles but the browser is giving the error

enter image description here

I am really not sure what I am doing wrong. Maybe it is my environment setup. When I comment out the first two lines that deal with dotenv all works fine.

Here is the code snippit.

import * as dotenv from 'dotenv'
dotenv.config({ path: __dirname + '/.env.local' })

const promise: Promise<string> = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('This is done!')
  }, 2000)
})

promise.then((data) => {
  console.log(data)
})

Usercaught syntaxError:”undefined”

I am creating an authentication system using MERN stack.
I already have completed 70% of my work.Till yesterday it was working flawlessly, but from today morning my app doesn’t render in browser and show it in the console

I am trying to solve it during the whole day but it’s not working

If anyone help me with it I will be grateful to him,,,,console view

Render the app on browser

Modal slider is not working when contents inserting via innerHtml js

I have two buttons on my site, you click on one, one gallery appears, on the other you click – another. This is javascript in php file in wordpress and php loop in javascript. I have used various image gallery scripts – for example bootstrap 5, magnific-popup.js. This all works fine normally, but if I insert this gallery via javascript innerHtml, the popup doesn’t work. The gallery itself appears, but does not work. When you click on the image, it just opens on a black screen and that’s it. How to make images pop up in a modal window and everything would work.

                jQuery(".nd-doc-btn").click(function() {
            const docsList = document.getElementById("nd-docs");
            docsList.style.opacity = 0;
            if (!jQuery(this).hasClass('nd-clicked-doc'))  {
                jQuery(".nd-doc-btn").removeClass('nd-clicked-doc');
                jQuery(this).removeClass('nd-doc-btn-doc');
                jQuery(this).addClass('nd-clicked-doc');
                if(jQuery(this).hasClass('nd-btn1')) {
                    
                    setTimeout(function(){ 
                   
                  jQuery(document).ready(function(){
                        insertModal();
                           });

                        function insertModal(){
                   
                    let modal1 = '<div class="row gy-4 pb-5 justify-content-center nd-docs"><?php if( have_rows('gallery_loop') ): while( have_rows('gallery_loop') ) : the_row(); ?><div class="col-12 col-sm-6 col-md-3 d-grid justify-content-center"><div class="magnific-img"><a class="image-popup-vertical-fit" href="<?php $img_gallery_loop = get_sub_field('img_gallery_loop'); echo esc_url($img_gallery_loop['url']); ?>" data-toggle="lightbox" data-gallery="example-gallery"><?php $img_data_caption = get_sub_field('img_data_caption');  if( !empty( $img_gallery_loop ) ): ?> <img src="<?php echo esc_url($img_gallery_loop['url']); ?>" alt="<?php echo esc_attr($img_gallery_loop['alt']); ?>" class="img-fluid" /><?php endif; ?></a></div><div class="nd-caption text-center"><p><?php echo $img_data_caption; ?></p></div></div><?php
                        endwhile; 
                        endif; ?></div>';

                        docsList.innerHTML = modal1;

                        docsList.style.opacity = 1;
                    }
                },700); 
             }
          } 
                          
        }); 

        <div class="container">

        <div id="nd-docs"></div> 
         
        </div>

How can I make an object property to return an object such as document.body?

W3school definition:

The body property sets or returns a document’s element.

Const docObj = {
    property1 : value1
    property2 : value2
    bodyProperty : //what do I write here to return bodyElementObject?

    // Here I can make a method
    bodyMethod : function(){
          return bodyElementObject;
    }
 };

I can write docObj.bodyMethod() to execute the return statement.

But for docObj.bodyProperty I’m not sure how?