Create textArea elements and copy button with jquery

I want to create a page containing three elements, one below the other: a text field (TextArea); a Copy button; a div element with empty initial text. And whenever the Copy button is clicked, the text typed in the TextArea should be transferred to the end of the text contained within the div. My code has a textArea, I already managed to put a copy button next to it, but I couldn’t think of a function to solve the problem. The idea is that it is solved only with jquery selectors. Finally, above this text box (textarea), the number of characters typed by the user should appear. In my js (jquery), I tried to create a function, but then I deleted it because I couldn’t. But I wanted to know how to do this.

<!DOCTYPE html>

<html lang="en">

<head>

  <title>jQuery</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</head>

<body>

<div class="container-fluid p-5 bg-primary text-white text-center">

  <h1>Criando páginas com jQuery</h1> 

</div>

  

<div class="container mt-5">

  <div class="row div1">

    <div class="col-sm-4 coluna1">

      <p class="classA">Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>

     

     

   // <p class="classB"> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris... </p><button id="dados" data-confirm="" data-iddocumento="189738" data-descricao="testte" type="button" class="btn btn-warning btn-xs 189738">Clique aqui</button>

      

    

    

    

     

      <ul>

        <li>Coffee</li>

        <li>Tea</li>

        <li>Milk</li>

      </ul>

    </div>

    <div class="col-sm-4 coluna2">

      <p class="classC">Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>

      <p class="classD">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>

    </div>

    <div class="col-sm-4 coluna3">      

      <p class="classE">Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>

      <p class="classF">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>

      <ul>

        <li>item 1</li>

        <li>item 2</li>

        <li>item 3</li>

      </ul>

    </div>

  </div>

  <div class="row div2">

    <h1>x caracteres</h1>

    <div class="col-12">

    <input class="contar" type="text" value="Vamos contar os caracteres?"/> <button id="copiar" data-confirm="" data-iddocumento="189738" data-descricao="testte" type="button" class="btn btn-warning btn-xs 189738">Copiar</button>

    </div>

  </div>

  <div class="row div3">

    <ul>

        <li>C++</li>

        <li>JAVA</li>

        <li>Python</li>

        <li>HTML/CSS</li>

      </ul>

  </div>

</div>

<div class="container-fluid rodape">

</div>

<script src="jquery.js"></script>

</body>

</html>
$('button').click(function(){

    $('.classB').text('Alterado pelo click do botão') });

How to call an Async function from a non Async function [duplicate]

I have a Typescript project with a function that is not Async. This function can’t be changed to async and this is giving me trouble to call an Async function and retrieve a value synchronously.

Is there a way I can await for my async function to evaluate before I continue the execution of the Main function? If I use the async keyword, it forces me to make the Main function async too.

Main function looks like this:

export const sortList = (
  list: Item[],
): Item[] => {
  const retrieveValueSynchronously = await getMyValue();
  return map(
         orderBy(list, item => item.timeStamp, "desc"),
         item => {
             ..... some more code here that uses **retrieveValueSynchronously** 
           }
      )
   };

And this is my async function:

 public async getMyValue(): Promise<string> {
    const { cachedMetadata } =
      await this.getCachedMetadata();

    return cachedMetadata;
  }

Javascript files not loading when hosting a website on digital ocean

I’ve built a web app with an express backend and using the ejs view engine.

When I run it on my computer it works fine but I’m trying to host in on digitalocean. I cloned it to the droplet(Ubuntu 22.10 x64) and served it on port 80. When I visited it in the browser at 46.101.145.210:80, I got these errors.

GET https://46.101.145.210/javascripts/cookieHandler.js net::ERR_CONNECTION_REFUSED               
GET https://46.101.145.210/javascripts/domain.js net::ERR_CONNECTION_REFUSED

Here’s my file structure,
enter image description here

Here’s the code in index.js.

const express = require("express");
const app = express();
const fs = require("fs");
const path = require("path")
const assert = require("assert");

const PORT = 80

app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(express.static('public'));

app.set("view engine", "ejs")

app.listen(PORT, () => {
    console.log("Server running on port " + PORT.toString());
});

const domains = ... // Not important

app.get("/", (req, res) => {
    res.render("index")
    //res.redirect("/domain")
})

app.get("/domain", (req, res) => {
    res.render("domain", {domains: domains})
})

I’ve tinkered with the firewall config and the express.static to see if it would make a difference. I couldn’t figure anything out though.

HTML Canvas produces wrong colors in Google Chrome

I have an PNG image in sRGB color space drawn in a canvas. I can’t find the reason why the colors are not accurate in Google Chrome because they are in FireFox and others softwares (like tiled). Here is a screenshot

enter image description here

(left is Google Chrome, right is Firefox ). Sample code

const canvas = document.querySelector("#canvas")
cost ctx = canvas!.getContext('2d')!
ctx.drawImage(myImg, 0, 0)

Call an object method once the chained methods are resolved

I would like to create a custom api service that will work similarly to the supabase-js library. Example:

const { data, error } = await supabase
  .from('cities')
  .select('name, countries(*)')
  .eq('countries.name', 'Estonia')

I cannot figure out how it is possible that the last method doesn’t have to be something like .get() (which would perform the fetch request)

Ideally, I would like the fetch to be called automatically after the chained methods are resolved – sth. like this:

const { data, pending, error } = await useProductsService()
                                             .whereIn('id', [123, 12, 521, 521])
                                             .whereLowerThan('price', 300)

note: I used supabase just as an example, I want to use this with a completely different API

I know how to do it with sth like a .get() method at the end, however, I’d like to do it without it, if possible.
It’s not a big deal to have to call one more method but I see it as an opportunity to learn something new as well.

Is it possible to do something like this? Or did I understand something wrong?

How do I transform a two-dimensional array of JavaScript primitives to an array of objects with dynamically generated properties?

Given a JavaScript multi-dimensional array (data1) is there an easy way to transform it into an array of objects with dynamically generated property names (data2)? ES6 is fine.

var data1 = [
  [1,"Text A",4,2,"Yes"],
  [2,"Text B",3,3,"Yes"],
  [3,"Text C",1,2,"No"]
]

var data2 = [
  {"0":1,"1":"Text A","2":4,"3":2,"4":"Yes"},
  {"0":2,"1":"Text B","2":3,"3":3,"4":"Yes"},
  {"0":3,"1":"Text C","2":1,"3":2,"4":"No"}
]

Return type of aws-sdk CognitoIdentityServiceProvider signUp

I have implemented the Cognito user creation with aws sdk. I can create user i the pool without any issue, Please advice me what is the return type I have to use in the

@Mutation(() =>

resolver,

@Mutation(() =>, {name:"Signup"})
async signUp(@Args('Signup') authRegisterRequest: RegisterRequestDto):Promise<any>{
    try{
     return await this.authService.signup(authRegisterRequest);
    }catch(error){
        throw new HttpException(error.message, 400)
    }
}

Service class signup function,

const cognito = new CognitoIdentityServiceProvider()
const result = await cognito
    .signUp({
      ClientId: this.configService.get<string>('AWS_COGNITO_CLIENT_ID'),
      Password: password,
      UserAttributes: [
        {
          Name: 'email',
          Value: email
        },
        {
          Name: 'name',
          Value: name
        },
      ],
      Username: email
    })
    .promise();
  return result;

I cannot find the correct type of return for the

@Mutation(() =>….., {name:”Signup”})
Please explain what is the return type I have to use here.

Unhandled error event -> AXIOS request: “Error: connect ECONNREFUSED 127.0.0.1:80”

Trying to download the response in HTML from web page in which I use minimist library , axios library and file system (in built library).

Here is the code in Javascript code

ReadHTMLfromWeb.js File

// node ReadHTMLfromWeb.js --url = "https://www.google.com/" --dest = "download.html"

let axios = require("axios");
let minimist = require("minimist");
let fs = require("fs");

let args = minimist(process.argv);

let dwnldPromise = axios.get(args.url);

dwnldPromise.then(function(response){
    let html = response.data;
    fs.writeFileSync(args.dest , html , "utf-8" );
})

But I face some problem and get this error

AxiosError.call(axiosError, error.message, code, config, request, response);
             ^
AxiosError: connect ECONNREFUSED 127.0.0.1:80
    at Function.AxiosError.from (E:JS PEPnode_modulesaxiosdistnodeaxios.cjs:825:14)
    at RedirectableRequest.handleRequestError (E:JS PEPnode_modulesaxiosdistnodeaxios.cjs:2961:25)
    at RedirectableRequest.emit (node:events:527:28)
    at ClientRequest.eventHandlers.<computed> (E:JS PEPnode_modulesfollow-redirectsindex.js:14:24)  
    at ClientRequest.emit (node:events:527:28)
    at Socket.socketErrorListener (node:_http_client:454:9)
    at Socket.emit (node:events:527:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  port: 80,
  address: '127.0.0.1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -4078,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: [Function: FormData] {
        LINE_BREAK: 'rn',
        DEFAULT_CONTENT_TYPE: 'application/octet-stream'
      },
      Blob: null
    },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/1.3.2',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'get',
    url: '=',
    data: undefined
  },
  request: <ref *2> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/=',
      method: 'GET',
      headers: [Object: null prototype] {
        Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/1.3.2',
        'Accept-Encoding': 'gzip, compress, deflate, br'
      },
      agents: { http: undefined, https: undefined },
      auth: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: { proxy: [Function: beforeRedirect] },
      hostname: 'localhost',
      port: '',
      agent: undefined,
      nativeProtocols: {
        'http:': {
          _connectionListener: [Function: connectionListener],
          METHODS: [
            'ACL',         'BIND',       'CHECKOUT',
            'CONNECT',     'COPY',       'DELETE',
            'GET',         'HEAD',       'LINK',
            'LOCK',        'M-SEARCH',   'MERGE',
            'MKACTIVITY',  'MKCALENDAR', 'MKCOL',
            'MOVE',        'NOTIFY',     'OPTIONS',
            'PATCH',       'POST',       'PROPFIND',
            'PROPPATCH',   'PURGE',      'PUT',
            'REBIND',      'REPORT',     'SEARCH',
            'SOURCE',      'SUBSCRIBE',  'TRACE',
            'UNBIND',      'UNLINK',     'UNLOCK',
            'UNSUBSCRIBE'
          ],
          STATUS_CODES: {
            '100': 'Continue',
            '101': 'Switching Protocols',
            '102': 'Processing',
            '103': 'Early Hints',
            '200': 'OK',
            '201': 'Created',
            '202': 'Accepted',
            '203': 'Non-Authoritative Information',
            '204': 'No Content',
            '205': 'Reset Content',
            '206': 'Partial Content',
            '207': 'Multi-Status',
            '208': 'Already Reported',
            '226': 'IM Used',
            '300': 'Multiple Choices',
            '301': 'Moved Permanently',
            '302': 'Found',
            '303': 'See Other',
            '304': 'Not Modified',
            '305': 'Use Proxy',
            '307': 'Temporary Redirect',
            '308': 'Permanent Redirect',
            '400': 'Bad Request',
            '401': 'Unauthorized',
            '402': 'Payment Required',
            '403': 'Forbidden',
            '404': 'Not Found',
            '405': 'Method Not Allowed',
            '406': 'Not Acceptable',
            '407': 'Proxy Authentication Required',
            '408': 'Request Timeout',
            '409': 'Conflict',
            '410': 'Gone',
            '411': 'Length Required',
            '412': 'Precondition Failed',
            '413': 'Payload Too Large',
            '414': 'URI Too Long',
            '415': 'Unsupported Media Type',
            '416': 'Range Not Satisfiable',
            '417': 'Expectation Failed',
            '418': "I'm a Teapot",
            '421': 'Misdirected Request',
            '422': 'Unprocessable Entity',
            '423': 'Locked',
            '424': 'Failed Dependency',
            '425': 'Too Early',
            '426': 'Upgrade Required',
            '428': 'Precondition Required',
            '429': 'Too Many Requests',
            '431': 'Request Header Fields Too Large',
            '451': 'Unavailable For Legal Reasons',
            '500': 'Internal Server Error',
            '501': 'Not Implemented',
            '502': 'Bad Gateway',
            '503': 'Service Unavailable',
            '504': 'Gateway Timeout',
            '505': 'HTTP Version Not Supported',
            '506': 'Variant Also Negotiates',
            '507': 'Insufficient Storage',
            '508': 'Loop Detected',
            '509': 'Bandwidth Limit Exceeded',
            '510': 'Not Extended',
            '511': 'Network Authentication Required'
          },
          Agent: [Function: Agent] { defaultMaxSockets: Infinity },
          ClientRequest: [Function: ClientRequest],
          IncomingMessage: [Function: IncomingMessage],
          OutgoingMessage: [Function: OutgoingMessage],
          Server: [Function: Server],
          ServerResponse: [Function: ServerResponse],
          createServer: [Function: createServer],
          validateHeaderName: [Function: __node_internal_],
          validateHeaderValue: [Function: __node_internal_],
          get: [Function: get],
          request: [Function: request],
          maxHeaderSize: [Getter],
          globalAgent: [Getter/Setter]
        },
        'https:': {
          Agent: [Function: Agent],
          globalAgent: Agent {
            _events: [Object: null prototype],
            _eventsCount: 2,
            _maxListeners: undefined,
            defaultPort: 443,
            protocol: 'https:',
            options: [Object: null prototype],
            requests: [Object: null prototype] {},
            sockets: [Object: null prototype] {},
            freeSockets: [Object: null prototype] {},
            keepAliveMsecs: 1000,
            keepAlive: false,
            maxSockets: Infinity,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            maxTotalSockets: Infinity,
            totalSocketCount: 0,
            maxCachedSessions: 100,
            _sessionCache: [Object],
            [Symbol(kCapture)]: false
          },
          Server: [Function: Server],
          createServer: [Function: createServer],
          get: [Function: get],
          request: [Function: request]
        }
      },
      pathname: '/='
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: <ref *1> ClientRequest {
      _events: [Object: null prototype] {
        response: [Function: bound onceWrapper] {
          listener: [Function (anonymous)]
        },
        abort: [Function (anonymous)],
        aborted: [Function (anonymous)],
        connect: [Function (anonymous)],
        error: [Function (anonymous)],
        socket: [Function (anonymous)],
        timeout: [Function (anonymous)]
      },
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: Socket {
        connecting: false,
        _hadError: true,
        _parent: null,
        _host: 'localhost',
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: true,
          emitClose: false,
          autoDestroy: true,
          destroyed: true,
          errored: Error: connect ECONNREFUSED 127.0.0.1:80
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 80
          },
          closed: true,
          closeEmitted: true,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: false,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          connect: [ [Function], [Function], [Function] ],
          free: [Function: onFree],
          close: [ [Function: onClose], [Function: socketCloseListener] ],
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          drain: [Function: ondrain]
        },
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: false,
          needDrain: false,
          ending: false,
          ended: false,
          finished: false,
          destroyed: true,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 169,
          writing: true,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: [Function: bound onFinish],
          writelen: 169,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: true,
          emitClose: false,
          autoDestroy: true,
          errored: Error: connect ECONNREFUSED 127.0.0.1:80
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 80
          },
          closed: true,
          closeEmitted: true,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: 'GET /= HTTP/1.1rn' +
          'Accept: application/json, text/plain, */*rn' +
          'User-Agent: axios/1.3.2rn' +
          'Accept-Encoding: gzip, compress, deflate, brrn' +
          'Host: localhostrn' +
          'Connection: closern' +
          'rn',
        _pendingEncoding: 'latin1',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 2,
        [Symbol(kHandle)]: null,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kSetNoDelay)]: false,
        [Symbol(kSetKeepAlive)]: true,
        [Symbol(kSetKeepAliveInitialDelay)]: 60,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0
      },
      _header: 'GET /= HTTP/1.1rn' +
        'Accept: application/json, text/plain, */*rn' +
        'User-Agent: axios/1.3.2rn' +
        'Accept-Encoding: gzip, compress, deflate, brrn' +
        'Host: localhostrn' +
        'Connection: closern' +
        'rn',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: Agent {
        _events: [Object: null prototype] {
          free: [Function (anonymous)],
          newListener: [Function: maybeEnableKeylog]
        },
        _eventsCount: 2,
        _maxListeners: undefined,
        defaultPort: 80,
        protocol: 'http:',
        options: [Object: null prototype] { path: null },
        requests: [Object: null prototype] {},
        sockets: [Object: null prototype] { 'localhost:80:': [ [Socket] ] },
        freeSockets: [Object: null prototype] {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        scheduling: 'lifo',
        maxTotalSockets: Infinity,
        totalSocketCount: 1,
        [Symbol(kCapture)]: false
      },
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/=',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *2],
PS E:JS PEP> npm i minimist

up to date, audited 11 packages in 1s

PS E:JS PEP> node ReadHTMLfromWeb.js --url = "https://www.google.com/" --dest = "download.html"

E:JS PEPnode_modulesaxiosdistnodeaxios.cjs:825
  AxiosError.call(axiosError, error.message, code, config, request, response);
             ^
AxiosError: connect ECONNREFUSED 127.0.0.1:80
    at Function.AxiosError.from (E:JS PEPnode_modulesaxiosdistnodeaxios.cjs:825:14)
    at RedirectableRequest.handleRequestError (E:JS PEPnode_modulesaxiosdistnodeaxios.cjs:2961:25)
    at RedirectableRequest.emit (node:events:527:28)
    at ClientRequest.eventHandlers.<computed> (E:JS PEPnode_modulesfollow-redirectsindex.js:14:24)  
    at ClientRequest.emit (node:events:527:28)
    at Socket.socketErrorListener (node:_http_client:454:9)
    at Socket.emit (node:events:527:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  port: 80,
  address: '127.0.0.1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -4078,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: [Function: FormData] {
        LINE_BREAK: 'rn',
        DEFAULT_CONTENT_TYPE: 'application/octet-stream'
      },
      Blob: null
    },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/1.3.2',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'get',
    url: '=',
    data: undefined
  },
  request: <ref *2> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/=',
      method: 'GET',
      headers: [Object: null prototype] {
        Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/1.3.2',
        'Accept-Encoding': 'gzip, compress, deflate, br'
      },
      agents: { http: undefined, https: undefined },
      auth: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: { proxy: [Function: beforeRedirect] },
      hostname: 'localhost',
      port: '',
      agent: undefined,
      nativeProtocols: {
        'http:': {
          _connectionListener: [Function: connectionListener],
          METHODS: [
            'ACL',         'BIND',       'CHECKOUT',
            'CONNECT',     'COPY',       'DELETE',
            'GET',         'HEAD',       'LINK',
            'LOCK',        'M-SEARCH',   'MERGE',
            'MKACTIVITY',  'MKCALENDAR', 'MKCOL',
            'MOVE',        'NOTIFY',     'OPTIONS',
            'PATCH',       'POST',       'PROPFIND',
            'PROPPATCH',   'PURGE',      'PUT',
            'REBIND',      'REPORT',     'SEARCH',
            'SOURCE',      'SUBSCRIBE',  'TRACE',
            'UNBIND',      'UNLINK',     'UNLOCK',
            'UNSUBSCRIBE'
          ],
          STATUS_CODES: {
            '100': 'Continue',
            '101': 'Switching Protocols',
            '102': 'Processing',
            '103': 'Early Hints',
            '200': 'OK',
            '201': 'Created',
            '202': 'Accepted',
            '203': 'Non-Authoritative Information',
            '204': 'No Content',
            '205': 'Reset Content',
            '206': 'Partial Content',
            '207': 'Multi-Status',
            '208': 'Already Reported',
            '226': 'IM Used',
            '300': 'Multiple Choices',
            '301': 'Moved Permanently',
            '302': 'Found',
            '303': 'See Other',
            '304': 'Not Modified',
            '305': 'Use Proxy',
            '307': 'Temporary Redirect',
            '308': 'Permanent Redirect',
            '400': 'Bad Request',
            '401': 'Unauthorized',
            '402': 'Payment Required',
            '403': 'Forbidden',
            '404': 'Not Found',
            '405': 'Method Not Allowed',
            '406': 'Not Acceptable',
            '407': 'Proxy Authentication Required',
            '408': 'Request Timeout',
            '409': 'Conflict',
            '410': 'Gone',
            '411': 'Length Required',
            '412': 'Precondition Failed',
            '413': 'Payload Too Large',
            '414': 'URI Too Long',
            '415': 'Unsupported Media Type',
            '416': 'Range Not Satisfiable',
            '417': 'Expectation Failed',
            '418': "I'm a Teapot",
            '421': 'Misdirected Request',
            '422': 'Unprocessable Entity',
            '423': 'Locked',
            '424': 'Failed Dependency',
            '425': 'Too Early',
            '426': 'Upgrade Required',
            '428': 'Precondition Required',
            '429': 'Too Many Requests',
            '431': 'Request Header Fields Too Large',
            '451': 'Unavailable For Legal Reasons',
            '500': 'Internal Server Error',
            '501': 'Not Implemented',
            '502': 'Bad Gateway',
            '503': 'Service Unavailable',
            '504': 'Gateway Timeout',
            '505': 'HTTP Version Not Supported',
            '506': 'Variant Also Negotiates',
            '507': 'Insufficient Storage',
            '508': 'Loop Detected',
            '509': 'Bandwidth Limit Exceeded',
            '510': 'Not Extended',
            '511': 'Network Authentication Required'
          },
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/=',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *2],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype] {
        accept: [ 'Accept', 'application/json, text/plain, */*' ],
        'user-agent': [ 'User-Agent', 'axios/1.3.2' ],
        'accept-encoding': [ 'Accept-Encoding', 'gzip, compress, deflate, br' ],
        host: [ 'Host', 'localhost' ]
      }
    },
    _currentUrl: 'http://localhost/=',
    [Symbol(kCapture)]: false
  },
  cause: Error: connect ECONNREFUSED 127.0.0.1:80
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 80
  }
}

Please solve my issue.

I want to download the html data of the webpage. But I facing the problem to get the response from the server.

How to Display Modal Popup Form in Angular using NgBootstrap and FormsModule

I will appreciate any support
I am trying to Display Modal Popup Form in Angular using NgBootstrap and FormsModule but the module NgbModule is not imported. I have:
node 16.15.1
cli 15.1.5
core 15.1.5
I go to the app.modules.ts and I add the module NgbModule in Imports but I get several errors

I have installed the packets:

font-awesome –save

bootstrap –save

I add @ng-bootstrap/ng-bootstrap

angular-material –save

One of the Errors:
enter image description here

{"name": "cragcity-website",
  "version": "0.0.1",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --open",
    "build": "ng build",
    "build-prod": "ng build --prod",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "15.1.4",
    "@angular/cdk": "15.1.4",
    "@angular/common": "15.1.4",
    "@angular/compiler": "15.1.4",
    "@angular/core": "15.1.4",
    "@angular/flex-layout": "12.0.0-beta.34",
    "@angular/forms": "15.1.4",
    "@angular/material": "15.1.4",
    "@angular/platform-browser": "15.1.4",
    "@angular/platform-browser-dynamic": "15.1.4",
    "@angular/router": "15.1.4",
    "@ckeditor/ckeditor5-angular": "^2.0.2",
    "@ckeditor/ckeditor5-build-classic": "^31.0.0",
    "@ckeditor/ckeditor5-upload": "^31.0.0",
    "angularx-social-login": "3.5.7",
    "bootstrap": "^5.2.3",
    "bootstrap-icons": "^1.10.2",
    "font-awesome": "^4.7.0",
    "jquery": "^3.6.3",
    "ng-recaptcha": "^8.0.1",
    "ngx-toastr": "14.0.0",
    "ngx-treeview": "10.0.2",
    "ngx-ui-loader": "13.0.0",
    "popper.js": "^1.16.1",
    "rxjs": "~6.6.0",
    "tslib": "2.2.0",
    "zone.js": "0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "15.1.5",
    "@angular/cli": "15.1.5",
    "@angular/compiler-cli": "15.1.4",
    "@types/jasmine": "3.8.1",
    "@types/node": "12.11.1",
    "jasmine-core": "3.8.0",
    "karma": "^6.4.1",
    "karma-chrome-launcher": "3.1.0",
    "karma-coverage": "2.0.3",
    "karma-jasmine": "4.0.1",
    "karma-jasmine-html-reporter": "1.7.0",
    "typescript": "4.9.5"
  }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { SocialLoginModule, FacebookLoginProvider, GoogleLoginProvider, SocialAuthServiceConfig } from "angularx-social-login";
import { environment } from '../environments/environment';

// components
import { AppComponent } from './app.component';
import { MtlComponent } from './components/mtl/mtl.component';
import { AvatarIconComponent } from './svg-icons/avatar/avatar-icon/avatar-icon.component';
import { HeartIconComponent } from './svg-icons/heart/heart-icon/heart-icon.component';
import { DownloadIconComponent } from './svg-icons/download/download-icon/download-icon.component';
import { ShareIconComponent } from './svg-icons/share/share-icon/share-icon.component';
import { CragcityLogoComponent } from './components/cragcity-logo/cragcity-logo.component';
import { CragcityFooterComponent } from './components/cragcity-footer/cragcity-footer.component';

import { LandingComponent } from './components/mtl/landing/landing.component';
import { SharedModule } from './components/shared/shared.module';
import { SubcategoryComponent } from './components/mtl/subcategory/subcategory.component';

import { RequestInterceptor } from './core/interceptors/request.interceptor';
import { ResponseInterceptor } from './core/interceptors/response.interceptor';
import { ToastrModule } from 'ngx-toastr';
import { NgxUiLoaderModule } from 'ngx-ui-loader';
import { ngxConfig } from './shared/constants'
import { SubCategoryUserComponent } from './components/mtl/subcategory/users/subcategoryuser.component';
import { SubcategoryUserAssignComponent } from './components/mtl/subcategory-user-assign/subcategory-user-assign.component';
import { TreeviewModule } from 'ngx-treeview';
import { DropdownIconComponent } from './svg-icons/dropdown/dropdown-icon/dropdown-icon.component';
import { AboutComponent } from './components/about/about.component';
import { ContactComponent } from './components/contact/contact.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ForgotPasswordComponent } from './components/account/forgot-password/forgot-password.component';
import { AccountModule } from './components/account/account.module';
import { AuthenticationComponent } from './components/authentication/authentication.component';
import { AuthenticationModule } from './components/authentication/authentication.module';
import { ResetPasswordComponent } from './components/authentication/reset-password/reset-password.component';
import { NewsFeedComponent } from './components/news-feed/news-feed.component';
import { PostComponent } from './components/news-feed/post/post.component';
import { NewsFeedDetailsComponent } from './components/news-feed/news-feed-details/news-feed-details.component';
import { SocialMShareComponent } from './components/mtl/socialM-share/socialM-share.component';




@NgModule({
  declarations: [
    AppComponent,
    MtlComponent,
    AvatarIconComponent,
    HeartIconComponent,
    DownloadIconComponent,
    ShareIconComponent,
    CragcityLogoComponent,
    CragcityFooterComponent,
    LandingComponent,
    SubcategoryComponent,
    SubCategoryUserComponent,
    SubcategoryUserAssignComponent,
    DropdownIconComponent,
    AboutComponent,
    ContactComponent,
    NewsFeedComponent,
    PostComponent,
    NewsFeedDetailsComponent,
    SocialMShareComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    ToastrModule.forRoot(),
    NgxUiLoaderModule.forRoot(ngxConfig),
    TreeviewModule.forRoot(),
    HttpClientModule,
    SocialLoginModule,
    SharedModule,
    AccountModule,
    NgbModule

  ],
  exports: [
    CragcityLogoComponent
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ResponseInterceptor,
      multi: true
    },
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: false,
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider(environment.googleClientId)
          },
          {
            id: FacebookLoginProvider.PROVIDER_ID,
            provider: new FacebookLoginProvider(environment.facebookAppId)
          }
        ]
      } as SocialAuthServiceConfig,
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular Change Detection Gives Up After secondary data load on SPA

I have a SPA that ultimately lists out a lot of data, but in batches.

I created a component at the bottom of the list, with a ‘Visibility’ directive so that when it is visible we make a new request to the dataset in a SQL server to get the next batch.

html-tag-for-component

    <app-infinity-scroll 
      [(pageNumber)]="page" 
      [displayPage]="displayPage" 
      [authd]="authd"
      [done]="done" 
      [numResults]="displayPage == 'tiles-hub' ? hubs.length : wallets.length"
      class="{{scrollVisible ? '' : 'hiddenDisplay'}}"
      trackVisibility
    ></app-infinity-scroll>

component-to-trigger-data-call

import { outputAst } from '@angular/compiler';
import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { DbSqlService } from 'services/db-sql.service';
import { TokenAuthService } from 'services/token-auth.service';
import { TrackVisibilityDirective } from 'src/app/directives/track-visibility.directive';
import { SortStyle } from 'src/app/interfaces/mvlot';
import { MatProgressBar } from '@angular/material/progress-bar';

@Component({
  selector: 'app-infinity-scroll',
  templateUrl: './infinity-scroll.component.html',
  styleUrls: ['./infinity-scroll.component.scss']
})
export class InfinityScrollComponent implements OnInit {

  @Input() pageNumber: number;
  @Input() displayPage: string;
  @Input() authd: boolean;
  @Input() done: boolean;
  @Input() numResults: number;

  @Output() pageNumberChange = new EventEmitter<number>();

  lastDisplay = '';
  loading: boolean = true;
  
  constructor(
    private visTrack: TrackVisibilityDirective
    , private cdr: ChangeDetectorRef
    , private dbApi: DbSqlService
    , private authService: TokenAuthService
  ) {
  }

  ngOnInit(): void {
    this.authService.UserAuthd.subscribe((res) => {
      // if (res) {
        this.dbApi.initGetWalletsHandler(0, 50, SortStyle.scoreDesc);
        this.pageNumber = 1;
      // }
    })

    this.visTrack.visibile.subscribe((val) => {
      if (!this.done) {
        this.loading = true;
        if (val) {
          if (this.displayPage == 'tiles') {
            this.dbApi.initGetWalletsHandler((this.pageNumber) * 50, 50, SortStyle.default);
            this.pageNumber += 1;
          }
          if (this.displayPage == 'tiles-hub') {
            this.dbApi.initGetHubsHandler((this.pageNumber) * 50, 50);
            this.pageNumber += 1;
          }
        }
      }
    })
  }
}

Some functions run, call out to a back-end, respond with data, where a listener is waiting.

    this.dbApi.resultObs.subscribe(val => {
      if (val.append != true) {
        this.results = [];
      } 

      if (val.reset) {
        this.page = 1;
      }

      val.data.data.forEach((b: any) => {
        var result: Collection;
        var existingResults = this.results.filter(w => w.ownerId == b.ownerId);
        
        if (existingResults.length == 0) {
          result = {
            ownerId: b.ownerId
            , totalScore: b.modifiedLandScore
            , filteredCount: b.filteredCount
            , totalLots: b.totalLots
            , totalPrice: b.totalPrice
            , name: ''
            , lands: []
            , type: CollectionType.b
          }

          

          result.bs.push(b);
          this.results.push(result);
        } else {
          result = existingResults[0];
          result.bs.push(b);
        }
      });

      this.resultDataSource = new MatTableDataSource(this.results);

      this.collectionType = CollectionType.b;
      this.uiService.loadingBar(false);
      this.done = val.data.data.length == 0;

      this.cdr.detectChanges();
    })

And, finally this is laid out for the user:

          <tr *ngFor="let result of results">
            <td>
              <display-block 
                [collection]="b" 
                [displayVertical]="displayVertical" 
                [displayCaseCount]="displayCaseCount" 
                [gridClassName]="gridClassName" 
                [authd]="authd" 
                [type]="result.type"
                [expanded]="results.length == 1"
                [isPhonePortrait]="isPhonePortrait"
                ></display-block>
            </td>
          </tr>

Everything works fine on the first grab of data.
And everything appears to work fine on the second pull, but for any of the items appended to the view with the second pull, ChangeDetector just seems to give up. I’ll trigger an action, that should modify the view, but nothing happens, unless I manully put in cdr, or I flip to a new window, or something, then they respond.

I’m going to continue trying to find a root cause, but at the moment, I’m out of ideas. There’s no prominent error message that would imply something broke. The items fromt the first batch still work. But the ones from the second will appear to lock up. until CDR is forced by an outside event.

I wanted to check here to see if anyone had any ideas on what may be causing this.
Also, here’s the declaration code for ‘trackVisibility’

import {
  Directive,
  ElementRef,
  EventEmitter,
  NgZone,
  OnDestroy,
  OnInit,
  Output,
} from '@angular/core';

@Directive({
  selector: '[trackVisibility]',
})
export class TrackVisibilityDirective implements OnInit, OnDestroy {
  observer!: IntersectionObserver;

  @Output()
  visibile = new EventEmitter<boolean>();

  constructor(private el: ElementRef<HTMLElement>, private ngZone: NgZone) {}

  ngOnInit(): void {
    this.ngZone.runOutsideAngular(() => {
      this.observer = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
           this.visibile.emit(e.isIntersecting);
        });
      });
      this.observer.observe(this.el.nativeElement);
    });
  }

  ngOnDestroy(): void {
    this.observer.disconnect();
  }
}

React components with common handler for update and create

I’m trying to find the best way to create and update items in a list. So, I have a form with item fields and I have the idea to provide a function (update or create) depending on the mode I choose. For example, I click the edit button and set the “update” mode, or I click the “add new item” button and set the “create” mode. In this case I don’t need to add two identical components with different click handlers (one for update, one for create), I will just provide a click handler depending on the mode state.
What do you think about this implementation?

import {useState} from "react";

enum MODES {
    view= "view",
    update= "update",
    create= "create",
}
const Page = () => {

    const [mode, setMode] = useState<MODES>(MODES.view);
    const [clickHandler, setClickHandler] = useState<() => void>();
    const [item, setItem] = useState({});

    const updateHandler = () => {};
    const createHandler = () => {};

    const setModeHandler = (mode: MODES) => {
        switch (mode) {
            case MODES.update: {
                setItem(selectedItem);
                setClickHandler(updateHandler);
            } break;
            case MODES.create: {
                setItem({});
                setClickHandler(createHandler);
            } break;
            default: {

            } break;
        }
    }


    return (
        <div>
            <div>
                <button onClick={() => {setModeHandler(MODES.update)}}>update</button>
                <button onClick={() => {setModeHandler(MODES.create)}}>create</button>
            </div>
            <ItemModal click={clickHandler} item={item} />
        </div>
    )
}

I attached the draft to better understand my question.

I would be glad to hear your opinion on this matter.

What do you think about this idea?
Is it okay or better to use to components with different handlers?

How to make a to-do list app present the input submitted to it

New coder here. I am trying to create a simple to-do list but clicking on the submit button is not returning any input.

Can you help me fix this? My code is below:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>To-Do List</title>
    <meta charset=""utf-8>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <style>
        #interface {
            background-color: rgb(220, 216, 216);
        }

    </style>

</head>
<body class="container" id="interface">
    <h1>To-Do List</h1>
    <h2>By Thabo Mtetwa</h2>
    <h4 id= "description">From office tasks, to household chores, and personal memos - this to-do list is a great way to keep track of them all.</h4>     
    <div class="container">
        <h3>Item</h3>
        <input type="text" id="item-input" placeholder="Add item here">
        <br><br>
        <div button type="button" class="btn btn-primary" id="submit">Submit</button>
        </div>
        <div id="todo-container">
        </div>
    </div>
    <script>
        let inputField = document.getElementById("item-input");
        let addButton = document.getElementById("submit");
        let listArea =  document.getElementById("todo-container");

        addButton.addEventListener("click", function() {
            var listItems = document.createElement("li");
            ListItems.innerText = listArea.value;
            listArea.appendChild(ListItems);
        });
    </script>
</body>
</html>

I created a variable to capture the information submitted in the input field, and set it to present this information in the list area below the input field. But this has not worked.

Audio captions not showing WebVTT

I’m trying to display my captions with my audio, and it seems like chrome loads it, but i dont see it on the screen, maybe it’s because it’s at the bottom of the div body?

I see the controls on the screen, but i don’t see the audio.

<audio id="player" autoplay="" src="data/audio/Voice 006.m4a">
        <source type="audio/m4a">
        
        <track src="dataaudiosubtitles.vtt" kind="captions" srclang="en" label="English" default="">
      

        
    </audio>

This is my .vtt file

WEBVTT

1
00:00.000 –> 00:02.111

  • Hi my name is sam

2
00:02.888 –> 00:06.555

  • I wanna see what letter names, letter sounds and words you know.

3
00:07.111 –> 00:10.555

  • Let’s answer some questions together and see how you do.