Response Error : [AxiosError: Network Error] at XMLHttpRequest.handleError on AVD and Iphone

I am new to react-native and facing this Axios network error on the register function in my firstApp

Here is my endpoint for registration

const app = express();
const port = 8000;
const cors = require("cors");
app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());

app.post("/register", (req, res) => {
 const { name, email, password, image } = req.body;
  // create a new User object
 const newUser = new User({ name, email, password, image });
 // save the user to the database
 newUser
.save()
.then(() => {
  res.status(200).json({ message: "User registered successfully" });
})
.catch((err) => {
  console.log("Error registering user", err);
  res.status(500).json({ message: "Error registering the user!" });
});

});

And here is the handleRegister function in RegisterScreens

// send a POST  request to the backend API to register the user
axios
  .post("http://localhost:8000/register", user)
  .then((response) => {
    console.log(response);
    Alert.alert(
      "Registration successful",
      "You have been registered Successfully"
    );
    setName("");
    setEmail("");
    setPassword("");
    setImage("");
  })
  .catch((error) => {
    Alert.alert(
      "Registration Error",
      "An error occurred while registering"
    );
    console.log("registration failed", error);
  });

I have tried adding a user on the web and it works, but it is not the same on AVD or my iPhone

Response Error : [AxiosError: Network Error] on AVD and Iphone

I am new to react-native and facing this Axios network error on the register function in my firstApp

Here is my endpoint for registration

const app = express();
const port = 8000;
const cors = require("cors");
app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());

app.post("/register", (req, res) => {
 const { name, email, password, image } = req.body;
  // create a new User object
 const newUser = new User({ name, email, password, image });
 // save the user to the database
 newUser
.save()
.then(() => {
  res.status(200).json({ message: "User registered successfully" });
})
.catch((err) => {
  console.log("Error registering user", err);
  res.status(500).json({ message: "Error registering the user!" });
});

});

And here is the handleRegister function in RegisterScreens

// send a POST  request to the backend API to register the user
axios
  .post("http://localhost:8000/register", user)
  .then((response) => {
    console.log(response);
    Alert.alert(
      "Registration successful",
      "You have been registered Successfully"
    );
    setName("");
    setEmail("");
    setPassword("");
    setImage("");
  })
  .catch((error) => {
    Alert.alert(
      "Registration Error",
      "An error occurred while registering"
    );
    console.log("registration failed", error);
  });

I have tried adding a user on the web and it works, but it is not the same on AVD or my iPhone

Wanting to make a new input/text box when I click a button

TIA for any help. I am trying to create a new field when I click a button. This is for a to-do list project. I tried to make a function that would create the new field. Then after creating the function I put it into an .eventListener when the button was clicked. I am not sure where to go from here.

Here is my code

text

**Javascript **

const button = document.querySelector('.createnew')
const field = document.querySelector('.field');

 function newField() {
 const inputElement = document.createElement("input.value");
 inputElement.setAttribute("type", "text");
  return field.appendChild(inputElement); 
 }

 button.addEventListener('click', newField);

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>To-Do</title>
</head>
<body>
    <h1 class="header">To-Do List</h1>
    <div class="container">

        <div class="form">
            <input class="field" type="text" placeholder="Input Text">
            <input class="check" type="checkbox">
        </div>  

        <button class="createnew">Add New Field</button>
    </div>

    <script src="index.js"></script>
</body>
</html>

Failed to fetch: Js code on Html template

In a JS code I’m using fetch to make GET requests to a url to obtain data in JSON format. The js code is located in my Django project and I use it in some templates. When I click on the button that activates the js script, it tells me that there is an error in the fetch, can someone help me?

function iniciarEscaneo() {
// Mostrar el mensaje de escaneo en progreso
document.getElementById("mensaje").innerText = "Escaneando NFC...";
document.getElementById("mensaje").style.display = "block";

// Establecer tiempo límite de espera en 10 segundos (10000 milisegundos)
var tiempoLimite = 10000;

// Realizar la solicitud GET a la URL para obtener el NFC
fetch("http://192.168.0.23:8081/read_nfc")
    .then(response => response.json())
    .then(data => {
        // Procesar la respuesta JSON
        if (data && data.uid) {
            // Actualizar el campo UID NFC en la plantilla con el UID obtenido
            document.getElementById("mensaje").innerText = "NFC leído correctamente.";
            document.getElementById("id_uid_nfc").innerText = data.uid;
        } else {
            document.getElementById("mensaje").innerText = "No se pudo leer el NFC.";
        }
    })
    .catch(error => {
        console.error('Error al obtener el NFC:', error);
        document.getElementById("mensaje").innerText = "Error al obtener el NFC: " + error.message;
    })
    .finally(() => {
        // Ocultar el mensaje después de un breve período de tiempo
        setTimeout(function() {
            if (document.getElementById("mensaje").innerText === "Escaneando NFC...") {
                document.getElementById("mensaje").innerText = "Tiempo de espera excedido. Intenta nuevamente.";
            }
            document.getElementById("mensaje").style.display = "none";
        }, tiempoLimite);
    });

}

I have tried to solve it by allowing cross origin but nothing.

String to Number with handlebar in JSReport

I am having a problem, and I cannot convert the strings (that correspond) into numbers with Handlebars

“this” is always String and object, even when it comes with a number (As seen in the image). What I want is that when it is an integer I convert it to a number and when it is a string I leave it original. Even when I create the report in xlsx, it doesn’t do the correct conversion, because string element shows correctly but numbers doesn’t see

{{#each this.properties}}
  {{#if (isNaN (convertToNumber this))}}
    <c t="inlineStr"><is><t>{{this}}</t></is></c>
  {{else}}
    <c t="n"><is><t>{{convertToNumber this}}</t></is></c>
  {{/if}}
{{/each}}

My handlebars functions
Debug example

How to deploy a website using .ejs on hosting services?

im trying to deploy a website using .ejs. The important thing is that the .ejs file is the “html” of the page (index.ejs).
https://imgur.com/a/VVt6JlY (Video demo)
As you can see everything works correctly on localhost but on github, netlify, cloudflare, etc. the page/client never loads. Does anyone know if I have to change the build deploy or something?

Cloudflare build view

Here’s the source: https://github.com/johandemierda/johans

Merge objects updating keys

Lets say I have two objects, for example

const obj1 = {
a: [{asd1: 1}, {asd2: 2}, {asd3: 3}]
}

const obj2 = {
a: [{asd4: 4}],
b: [{a: "asd"}, {b: "asd"}]
}

I have to merge the two objects having a result like this

obj3 = {
a: [{asd1: 1}, {asd2: 2}, {asd3: 3}, {asd4: 4}]
b: [{a: "asd"}, {b: "asd"}]
}

What would be the most effective way to accomplish this?

I can’t download the Terser library

For reasons of version incompatibility, the UglifyJs library is not supporting ES6, so I am trying to install the Terser library in webpack and the following error occurs:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/webpack
npm ERR! dev webpack@”4.8.1″ from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@”^5.1.0″ from [email protected]
npm ERR! node_modules/terser-webpack-plugin
npm ERR! dev terser-webpack-plugin@”*” from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with –force, or –legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I tried to install it in the terminal with the command npm install terser-webpack-plugin –save-dev, but I got an error, I expected the library to be downloaded normally

Unexpected identifier ‘bodyText’. Parse error

I have a problem in JavaScript. To my code, I want to add a function programmed in PHP, but I don’t know how to do it. Let me explain, if I add the code it works, but the rest of the code breaks… Giving me the error: Unexpected identifier ‘bodyText’. parse error.

What this code does for me is preview a message before being published. I want the preview to read me a programmed bbcode

Clean code:

// Show the preview section.
                var preview = XMLDoc.getElementsByTagName('forum')[0].getElementsByTagName('preview')[0];
                setInnerHTML(document.getElementById('preview_subject'), preview.getElementsByTagName('subject')[0].firstChild.nodeValue);

                var bodyText = '';
                for (var i = 0, n = preview.getElementsByTagName('body')[0].childNodes.length; i < n; i++)
                    bodyText += preview.getElementsByTagName('body')[0].childNodes[i].nodeValue;

                setInnerHTML(document.getElementById('preview_body'), bodyText);
                document.getElementById('preview_body').className = 'post';

My modification:

// Show the preview section.
                var preview = XMLDoc.getElementsByTagName('forum')[0].getElementsByTagName('preview')[0];
                setInnerHTML(document.getElementById('preview_subject'), preview.getElementsByTagName('subject')[0].firstChild.nodeValue);

                var bodyText = '';
'parse_yt('bodyText');
                for (var i = 0, n = preview.getElementsByTagName('body')[0].childNodes.length; i < n; i++)
                    bodyText += preview.getElementsByTagName('body')[0].childNodes[i].nodeValue;

                setInnerHTML(document.getElementById('preview_body'), bodyText);
                document.getElementById('preview_body').className = 'post';

With parse_yt(‘bodyText’) (this is a php function) it gives me the format I want, but there is something wrong in the way I put it, which gives me the error:

SyntaxError: Unexpected identifier ‘bodyText’. Parse error.

How could I fix it? Thank you!!

Highcharts – How do I add a strikethrough effect on legend item?

I’m utilizing Highcharts in my code. Currently, when a user clicks on a legend item (for example, “ABC”), the corresponding pie labeled “ABC” changes to a gray color. Upon clicking again, the gray color is removed and the pie reverts to its original color. Now, I wish to enhance this functionality by adding a strikethrough effect to the “ABC” legend item when the pie turns gray, and removing the strikethrough when the pie returns to its original color.

Highcharts.chart('container', {
  series: [{
    type: 'pie',
    data: [1, 2, 3, 4],
    showInLegend: true,
    point: {
      events: {
        legendItemClick: function() {
          var originalColor = this.options.originalColor; // Retrieve original color from options
          var newColor = (this.color === 'gray') ? originalColor : 'gray'; // Toggle between gray and original color
          
          // Toggle visibility of data labels
          var showDataLabels = (newColor !== 'gray');

          this.update({
            color: newColor,
            dataLabels: {
              enabled: showDataLabels
            }
          });
          
          return false;
        }
      }
    },
    events: {
      afterInit: function() {
        // Store original color for each point
        this.points.forEach(function(point) {
          point.options.originalColor = point.color;
        });
      }
    }
  }],
  accessibility: {
    enabled: false,
  },
});
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container"></div>

How to use silentmantra/benchmark?

Here’s on Stackoverflow I often benchmark JS solutions in my answers and people ask how they could write own benchmarks. So this post is rather an answer due to the convenient code snippet tool, which the benchmark could be injected directly into. So please don’t downvote or close, just skip if not interested, any updates could go as answers. Ask your questions as comments.

The home page: https://github.com/silentmantra/benchmark
For examples you could check https://stackoverflow.com/search?tab=newest&q=user%3a14098260%20benchmark&searchOn=3

Code for benchmarking should be included in <script> tag inline. Then you should load the benchmark tool’s code, you do this either by

  1. With <script>. Make sure it’s loaded after your <script> with benchmarks (You can defer (with type="module" also)):
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
  1. Directly inside your benchmark code in any place (usually as the last line):
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));

As you see with /* @skip */ you can exclude a line of code from benchmarked code but execute it initially in <script>.

After loading the tool transform your <script> in an UI to show results of your benchmarks and to execute them. The results are displayed as JSON and cut to the first 500 characters or so.

A simple benchmark could be

  1. Some code to execute before each benchmark
  2. One or several solutions beginning with
// @benchmark Solution 1

where everything following @benchmark is the solution’s name.

  1. The execution result of a solution is the result of the last line (execution is done with eval()).
    const input = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua';
    
    // @benchmark Array::reverse()
    input.split('').reverse().join('');
    
    // @benchmark string concat
    let result = '';
    for(let i = input.length - 1; i >= 0; i--){
      result += input[i];
    }
    result;
    
    /*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));

After clicking RUN the tool estimates how many cycles to run each solution so the average time for a solution would be not less than 100ms and runs each solution 5 times by default (you can change it with the times number input). After running you can copy the results as a markup. So the above benchmark gives:

` Chrome/122
------------------------------------------------------
string concat     1.00x | x1000000 399 404 422 435 441
Array::reverse()  3.08x |  x100000 123 124 130 131 139
------------------------------------------------------
https://github.com/silentmantra/benchmark `

The first solution is the fastest which is marked as 1x. The other solutions are marked how they are slower than the top solution. The next column is how many cycles the solution was run, and the next 5 (number of times the solution was run) are milliseconds taken to run the cycles with the minimum time as the first (sorted asc). Basically based on my experience the minimum time is the most presentable value of how good a solution could perform.

You can set the times and cycles manually (sometimes for heavy solutions you could prefer manually setting the cycles to 1):

const TIMES = 3, CYCLES = 1000000;
const input = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua';

// @benchmark Array::reverse()
input.split('').reverse().join('');

// @benchmark string concat
let result = '';
for(let i = input.length - 1; i >= 0; i--){
  result += input[i];
}
result;

/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));

Algorithms have different time complexity so it’s possible to benchmark solutions with different input size. For that we have 3 variables:

  1. $chunk – a chunk from which the input is composed. Could be a string, an array or a function returning either of them.
  2. $input – an array or a string to fill with chunks.
  3. $chunks – an array of numbers of chunks to run (default [1, 10, 100, 1000] – no need to define).

Let’s check with a string:

const $chunk = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua';
let $input = '';

// @benchmark count stupid
{
  const chars = {};
  for(let i = 0; i < $input.length; i++){
    const char = $input[i];
    chars[char] ??= $input.split('').filter(c => c === char).length;
  }
  chars;
}

// @benchmark count smart
{
  const chars = {};
  for(let i = 0; i < $input.length; i++){
    const char = $input[i];
    chars[char] ??= 0;
    chars[char]++;
  }
  chars;
}
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));
` Chrome/122
--------------------------------------------------------------------------------
>                   n=122      |     n=1220     |    n=12200    |    n=122000   
count smart    1.00x x100k 284 | 1.00x x10k 183 | 1.00x x1k 186 | 1.00x x100 186
count stupid   2.56x x100k 727 | 3.33x x10k 609 | 3.40x x1k 633 | 7.26x  x10 135
--------------------------------------------------------------------------------
https://github.com/silentmantra/benchmark `

A top solution is the best with the most input size.

Note that you could use {} block to create a block scope to run a solution in it to avoid variable clashing.

With a chunk function:

const $chunks = [100, 1000, 10000, 100000];
const $chunk = () => [Math.random()];
const $input = [];

// @benchmark count stupid
{
  const chars = {};
  const allNums = $input.map(n => n.toString().slice(2)).join('');

  for(let i = 0; i < allNums.length; i++){
    const char = allNums[i];
    chars[char] ??= allNums.split('').filter(c => c === char).length;
  }
  chars;
}

// @benchmark count smart
{
  const chars = {};
  $input.forEach(num => {
    for(const char of num.toString().slice(2)){
      chars[char] ??= 0;
      chars[char]++;
    }
  });
  chars;
}
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));
` Chrome/122
------------------------------------------------------------------------------
>                  n=100      |    n=1000     |    n=10000     |   n=100000   
count smart    1.00x x10k 172 | 1.00x x1k 191 | 1.00x x100 246 | 1.00x x10 337
count stupid   4.19x x10k 720 | 4.01x x1k 766 | 5.53x  x10 136 | 5.43x  x1 183
------------------------------------------------------------------------------
https://github.com/silentmantra/benchmark `

If you need some code executed before the cycles, use // @run. For example you could introduce a set of functions/classes used in a solution (initializing them in each cycle is expensive and skews results).

const $chunks = [100, 1000, 10000, 100000];
const $chunk = () => [Math.random()];
const $input = [];

// @benchmark count stupid
{
  const countChars = $input => {
    const chars = {};
    const allNums = $input.map(n => n.toString().slice(2)).join('');

    for(let i = 0; i < allNums.length; i++){
      const char = allNums[i];
      chars[char] ??= allNums.split('').filter(c => c === char).length;
    }
    return chars;
  };
  // @run
  countChars($input);
}

// @benchmark count smart
{
  const countChars = $input => {
    const chars = {};
    $input.forEach(num => {
      for(const char of num.toString().slice(2)){
        chars[char] ??= 0;
        chars[char]++;
      }
    });
    return chars;
  };
  // @run
  countChars($input);
}
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));

How to change textfield color on Materials Component Web

I am using google material-components-web and I am trying to change the color of the outline of this textfield (wish to change the outline and text color when it’s focused).

Code is:

<label class="mdc-text-field mdc-text-field--outlined">
  <span class="mdc-notched-outline">
    <span class="mdc-notched-outline__leading"></span>
    <span class="mdc-notched-outline__notch">
      <span class="mdc-floating-label" id="my-label-id">Your Name</span>
    </span>
    <span class="mdc-notched-outline__trailing"></span>
  </span>
  <input type="text" class="mdc-text-field__input" aria-labelledby="my-label-id">
</label>

enter image description here

I currently tried changing the –mdc-theme-primary but that only changes the outline color not the colour of the text when focused.

When dynamically appending script into iframe, Content Security Policy isn’t updated

I want to dynamically append a script tag into my website.

The src needs to be dynamic, where a variable determines what subdomain to request the script from. Due to the unique nature of my site, This is my CSP policy:

Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-eval' 'self'; frame-ancestors 'none'; worker-src 'none'; navigate-to 'none';

I am trying to add a script, using this code:

let subdomain = // my logic

let my_frame = document.createElement("iframe");
my_frame.csp = "script-src *.example.com";
document.body.appendChild(my_frame);

my_frame.contentWindow.document.write(`<script src="//${subdomain}.example.com"></script>`);

This code errors out:

cant load script because it violates CSP directive unsafe-eval

From what I understand about CSP, more restrictive directives take precendence. Since script-src *.example.com is more restrictive than unsafe-evaland self, my subdomain should be allowed. I will never use example.com alone, so I have only added the directive for the subdomain.

What is going wrong here?

Note: I cannot change the current Content Security Policy.