How get a web API written in C# .NET 8.0 to send a 200 response to satisfy a CORS preflight request?

I built an ASP.NET Core 8.0 Web API which works fine in Google script and from a web site built from notepad. However when I am trying to communicate with it from an external site, it throws a CORS error

Access to fetch at ‘https://a.someting.edu/Newsletter/api/newsletter’ from origin ‘https://t4.something.edu’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status

My Program.cs file:

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy =>
                      {
                          policy.WithOrigins("https://t4.something.edu")
                                .AllowAnyHeader()
                                .AllowAnyMethod();
                      });
});

builder.Services.AddControllers();

// context 
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .AddCommandLine(args)
    .AddUserSecrets<Program>(true)
    .Build();

builder.Services.AddDbContext<NewsletterContext>(option =>
{
    option.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddTransient<IApiKeyValidation, ApiKeyValidation>();
builder.Services.AddScoped<ApiKeyAuthFilter>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

Frontend HTML JavaScript Code

<script>
        function send() 
        {
            var url = 'https://a.something.edu/News/api/news';
            var headers = {
                    'X-API-Key' : "something1234",
                    'Accept': "application/json",
                    'Content-Type': "application/json;charset=utf-8"
            };
            var data = {
                    "email" : document.getElementById("customerEmail").value
            };
            
            var payload = JSON.stringify(data);
            
            var options = {
                method: "POST",
                headers: headers,
                body: payload
            };
            
            try {
                var response = fetch(url, options);
            }catch(error) {
                alert('Error is : ' + error);
            }
            alert('Response is - ' + response);
        }
</script>

Included in my program.cs file is cors middleware that I found on Microsoft learn cors, same issue and am not sure I set that up correctly as I still have to set the response header on the web server to Access-Control-Allow-Origin = *. Which is verified by the web.config file:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Controller code

 [Route("api/[controller]")]
 [ApiController]
 public class NewsletterController(NewsletterContext context) : ControllerBase
 {
     private readonly NewsletterContext _context = context;

     [HttpPost]
     public async Task<ActionResult<NewsletterItem>> PostNewsletterItem(NewsletterItem newsletterItem)
     {
        _context.Newsletter_Emails.Add(newsletterItem);

         try
         {
             await _context.SaveChangesAsync();

         }
         catch (DbUpdateConcurrencyException)
         {
            throw;
         }
         return Ok("The record has been saved correctly");
     }
 }

Model code

namespace NewsletterEmails.Models
{
   public class NewsletterItem
   {
       [Key]
       public required string Email { get; set; }
    }
}

I tried to set the mode to no-cors, however that results in an unsupported media type error 415.

JavaScript incorrectly changing input [closed]

When I run this script on my localhost instead of checking for the value, it corrects the pin instead.

This is my first time using JavaScript but I have run if else statements identical to this one in multiple other languages with no issue. I just don’t see where the issue is coming from in the code.

When I press submit, the pin changes to “1234” and it displays the “Correct” message regardless of what I have typed in or if I just leave it as

function PINCheck() {
  var result = document.getElementById("ErrorMessage")
  var pin = document.getElementById("Pin")

  if (pin.value = "1234") {
    result.innerText = "Correct"
  } else if (pin.value != "1234") {
    pin.innerText = "******"
    result.innerText = "Incorrect PIN"
  }

}
<container class="container">
  <label for="Pin">PIN</label><br>
  <input type="text" id="Pin" name="Pin" value="******"><br>
  <button onclick="PINCheck()">SUBMIT</button>
  <p id="ErrorMessage">---</p>
</container>

Why Javascript dblclick event is running at Chrome but isn’t running at the Edge?

I am new to the javascript. I want to double click a button and write something to the console but the code I use doen’t work.
The code here: btn.addEventListener("dblclick",function);

This code didn’t work at the Microsoft Edge. I looked the documentation. At the documentation there are two way.

First way is (this way is same with my way):

addEventListener("dblclick", (event) => {});

Second way is:

ondblclick = (event) => {};

I tried two way but it didn’t work. And than I changed ‘dblclick’ to ‘ondblclick’ but it didn’t work again. But at this times I didn’t take any error or warning. At the last time I tried at the Google Chrome it worked successfully.

Why the same code worked at the Chrome but didn’t work at the Edge? What can I do to solve this problem?

Printing an svg from a webpage

I want to make a button to print a generated barcode as an svg or as an png

HTML code:

<input class="form-control" type="text" placeholder="put the code here">
        <svg class="hidden" id="barcode" onclick="window.print(this)" id="svgObject" width="100" height="100"></svg>
        <button class="btn btn-outline-danger">Generate</button>
        <input class="btn btn-outline-danger" type="button" onclick="printDiv('print-content')" value="print"/>
    </section>
    <script src="jsBarcode.code128.min.js"></script>
    <script src="index.js"></script>

js code:

document.querySelector("button").addEventListener("click" , function() {
    var text = document.querySelector("input").value;
    JsBarcode("#barcode", text);
    document.getElementById("barcode").classList.remove("hidden")
});
function printDiv(divName) {
    var printContents = document.getElementById(barcode).outerHTML;
    w=window.open();
    w.document.write(printContents);
    w.print();
    w.close();
}

I am using this js generator :https://lindell.me/JsBarcode/

when is use this code It prints it as a pdf not an SVG or any image format

How to get a message from workbox-broadcast-update even if there is not update?

I’m trying workbox and service-worker for the first time today.

I’m using the stale-while-revalidate strategy with the BroadcastUpdatePlugin.

Everything works:

  • the browser starts a call

  • the Service Worker with Workbox return the cached response and starts a revalidation call

  • if the revalidation response is different I get a message! Great!

What I don’t know is how to receive an event even if there is NO UPDATE from the revalidation call.

This is the code I’m using:

importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/7.1.0/workbox-sw.js"
);

self.skipWaiting();

workbox.core.clientsClaim();

workbox.routing.registerRoute(
  ({ url }) => url.pathname.startsWith("/images/avatars/"),

  new workbox.strategies.StaleWhileRevalidate({
    plugins: [new workbox.broadcastUpdate.BroadcastUpdatePlugin()],
  })
);

I would like something like this:

workbox.routing.registerRoute(
  ({ url }) => url.pathname.startsWith("/images/avatars/"),

  new workbox.strategies.StaleWhileRevalidate({
    plugins: [new workbox.broadcastUpdate.BroadcastUpdatePlugin({
        callback: (response) => {
            if (response.isNew()) {
                const message = {};

                sendMessageToClient(message);
            }
        }
    })],
  })
);

Is there a way?

cant open capacitor app in dev mode for physical device android using quasar but works on emulator

Im using Quasar and capacitor. I started a brand new project. Did build the app using:

quasar build -m capacitor -T android

I then open android studio. Using an emulator with API Tiramisu and the app do open.
I then change to my physical device ín developer mode. Also using Android 14 (tiramsiu). But the app seems to freeze. Nothing happens. After a while connection times out. I have tried on different devices with the same result.

variables.gradle:

minSdkVersion = 23 
compileSdkVersion = 34
targetSdkVersion = 34

using java 17

gradle-wrapper.properties:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-8.2.1-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

package.json:

"quasar": "^2.16.0"
"vue": "^3.4.18"
"@quasar/app-vite": "^1.9.0",

and package.json in src-capacitor:

"dependencies": {
    "@capacitor/android": "^6.0.0",
    "@capacitor/app": "^6.0.0",
    "@capacitor/cli": "^6.0.0",
    "@capacitor/core": "^6.0.0"
  }

what else can be relevant? Any hint of what to do?

Repurposing neural network trained using the NEAT-Python library

I’m making a program to train an AI agent to play the game of snake in Python using the NEAT-Python library. After training, I want to export the network and then use it to visualize how it makes decisions in another language (such as JavaScript). Is it possible to export the network and then use it outside of Python? I tried looking at the PyTorch-NEAT library from Uber Research, but it wasn’t exactly what I was looking for.

Autocomplete for built in JavaScript functions not working inside custom made functions

I’m experiencing an issue with IntelliSense (autocomplete) in my JavaScript development environment (VS Code). Specifically, autocomplete for built-in JavaScript methods like slice() is not working inside custom functions. While the function itself executes correctly, IntelliSense fails to provide suggestions or autocomplete options when typing . after the variable name within the function. However, the same methods work and are suggested as expected when used outside of custom functions.

See example images:
enter image description here
enter image description here

Tried renaming variables to avoid conflicts with built-in JavaScript names.
Restarted VS Code.
Created a new file to test if the issue persists.

Highcharts Sankey Chart: Only Data Labels Displayed, No Nodes or Links Visible

I’m working on a Sankey chart using Highcharts, but I’m encountering an issue where only the data labels are being displayed, while the nodes and links (edges) are not visible at all.

Here is the code and below that a link to a JSFiddle:

Highcharts.chart('container', {
    title: {
        text: 'Luxury Car Ownership',
        style: {fontSize: 20}
    },
    accessibility: {
        point: {valueDescriptionFormat: '{index}. {point.from} to {point.to}, {point.weight}.'}
    },
    tooltip: {
        headerFormat: null,
        pointFormat:
      '{point.fromNode.name} u2192 {point.toNode.name}: {point.weight} people',
        nodeFormat: '{point.name}: {point.sum} people'
    },
    series: [{
      nodePadding: 20,
      borderColor: "#1a1a1a",
      borderWidth: 1,
        keys: ['from', 'to', 'weight'],
        nodes: [
            {id: '25 - 50 years old', column: 1},
    
            {id: 'Owns Luxury Car', column: 2}, 
            {id: 'Does Not Own Luxury Car', column: 2}, 
    
            {id: 'Luxury Car with Ferrari', column: 3}, 
            {id: 'Luxury Car with Lamborghini', column: 3}, 
            {id: 'Luxury Car with Porsche', column: 3}, 
            {id: 'Luxury Car with Rolls-Royce', column: 3}, 
            {id: 'Luxury Car with Others', column: 3}, 

            {id: 'No Luxury Car but Interested', column: 4, offset: 100}, 
            {id: 'No Luxury Car and Undecided', column: 4, offset: 100}, 
            {id: 'No Luxury Car and Not Interested', column: 4, offset: 100},
    
            {id: 'Ferrari Loyal', column: 5, offset: -150}, 
            {id: 'Ferrari Disloyal', column: 5, offset: -150}, 
            {id: 'Lamborghini Loyal', column: 5, offset: -150}, 
            {id: 'Lamborghini Disloyal', column: 5, offset: -150}, 
            {id: 'Porsche Loyal', column: 5, offset: -150}, 
            {id: 'Porsche Disloyal', column: 5, offset: -150}, 

            {id: 'Ferrari Disloyal to Rolls-Royce', column: 6, offset: -150}, 
            {id: 'Ferrari Disloyal to Others', column: 6, offset: -150}, 
            {id: 'Lamborghini Disloyal to Rolls-Royce', column: 6, offset: -150}, 
            {id: 'Lamborghini Disloyal to Others', column: 6, offset: -150}, 
            {id: 'Porsche Disloyal to Rolls-Royce', column: 6, offset: -150}, 
            {id: 'Porsche Disloyal to Others', column: 6, offset: -150}, 

            {id: 'Rolls-Royce Total Potential for Luxury Cars', column: 7}
        ],
        data: [
            ['25 - 50 years old', 'Owns Luxury Car', 7014552], 
            ['25 - 50 years old', 'Does Not Own Luxury Car', 19270034], 

            ['Owns Luxury Car', 'Luxury Car with Ferrari', 1456019], 
            ['Owns Luxury Car', 'Luxury Car with Lamborghini', 655591], 
            ['Owns Luxury Car', 'Luxury Car with Porsche', 789634],
            ['Owns Luxury Car', 'Luxury Car with Rolls-Royce', 618173],
            ['Owns Luxury Car', 'Luxury Car with Others', 4690510], 

            ['Does Not Own Luxury Car', 'No Luxury Car but Interested', 2172559], 
            ['Does Not Own Luxury Car', 'No Luxury Car and Undecided', 15569023], 
            ['Does Not Own Luxury Car', 'No Luxury Car and Not Interested', 1528450], 
            
            ['Luxury Car with Ferrari', 'Ferrari Loyal', 465784], 
            ['Luxury Car with Ferrari', 'Ferrari Disloyal', 990234], 
            ['Ferrari Disloyal', 'Ferrari Disloyal to Rolls-Royce', 153567], 
            ['Ferrari Disloyal', 'Ferrari Disloyal to Others', 836667],
            ['Ferrari Disloyal to Rolls-Royce', 'Rolls-Royce Total Potential for Luxury Cars', 153567], 

            ['Luxury Car with Lamborghini', 'Lamborghini Loyal', 319094], 
            ['Luxury Car with Lamborghini', 'Lamborghini Disloyal', 336497], 
            ['Lamborghini Disloyal', 'Lamborghini Disloyal to Rolls-Royce', 50917], 
            ['Lamborghini Disloyal', 'Lamborghini Disloyal to Others', 285579], 
            ['Lamborghini Disloyal to Rolls-Royce', 'Rolls-Royce Total Potential for Luxury Cars', 50917], 

            ['Luxury Car with Porsche', 'Porsche Loyal', 131638], 
            ['Luxury Car with Porsche', 'Porsche Disloyal', 657996], 
            ['Porsche Disloyal', 'Porsche Disloyal to Rolls-Royce', 100700], 
            ['Porsche Disloyal', 'Porsche Disloyal to Others', 557296], 
            ['Porsche Disloyal to Rolls-Royce', 'Rolls-Royce Total Potential for Luxury Cars', 100700],

            ['No Luxury Car but Interested', 'Rolls-Royce Total Potential for Luxury Cars', 2172559], 
            ['No Luxury Car and Undecided', 'Rolls-Royce Total Potential for Luxury Cars', 15569023]
        ],
        type: 'sankey',
        name: 'Sankey demo series'
    }]
});

https://jsfiddle.net/Niggels/paosudhb/7/

Current Workaround:

The only way I’ve managed to get the nodes and links to display is by setting minLinkWidth in the series to a value like 10. However, this causes all the links to have the same thickness, which is not what I need. I require the links to be proportional to their respective values (weights).

Has anyone experienced a similar issue, or does anyone have suggestions on how to resolve this? I’m looking for a solution that allows the nodes and links to display correctly without forcing a minimum link width that disrupts the proportionality of the links.

Thanks in advance!

Things I’ve Tried:

  • Data Label Overlap: I’ve tried enabling and disabling
    dataLabels.allowOverlap, but this didn’t resolve the issue.
  • Chart Dimensions: I’ve adjusted the height and width of the chart to
    ensure there’s enough space for everything to display properly.
  • Node and Link Verification: I’ve double-checked that all nodes are
    referenced in the links, and vice versa, to ensure no missing
    connections.

EDIT: Ok, somehow i fixed it. I played with the column numbering and i think I need the column 0 to start with. In the previous, corrupted chart I started with column 1. Now i started with Column 0 and that seems to have fixed the problem!

In react, formik and yup how to skip validation if dynamic array value if undefined or empty make it optional

This is my aaray :

translator_services: (4) [empty × 3, {translator_category_description: "sa",translator_category_id: "6672a5a8b07e9bc1b7e36a5c",translator_category_type_id: ['6672a5a8b07e9bc1b7e36a5a']}]

This the error from Yup :

translator_services: Array(3)<br>
0: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
1: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
2: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>

This is validation code :

translator_services: Yup.array().of(
    Yup.object().shape({
      translator_category_id:
        Yup.string().required("Required"),
      translator_category_description:
        Yup.string().nullable().required("Description is required."),
      
      translator_category_type_id: Yup.array().nullable().min(
        1,
        "Select at least one service type"
      ),
    })
  ),

Should only validate if the array value is defined or not empty else skip the validation.
Thanks in advance

Why are the edit events not triggered?

I have a map (full example here)

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
    integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
    crossorigin="" />

<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
    integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
    crossorigin=""></script>

<link rel="stylesheet" href="https://unpkg.com/@geoman-io/leaflet-geoman-free@latest/dist/leaflet-geoman.css" />

<script src="https://unpkg.com/@geoman-io/leaflet-geoman-free@latest/dist/leaflet-geoman.js"></script>

...

<div id="map" style="height: 900px;"></div>

  var map = L.map('map', { pmIgnore: false }).setView([51.505, -0.09], 13);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  map.pm.addControls({
    position: 'topleft',
    drawCircleMarker: false,
    rotateMode: false,
  });

also i have a some logic to add some data to the map


  var shapeField = document.getElementById('shape-field').value;
  var savedPolygonData = shapeField ? JSON.parse(shapeField) : null;

  if (savedPolygonData) {
    L.geoJSON(savedPolygonData).eachLayer(function (layer) {
      allLayers.push(layer);
      layer.addTo(map);
    });
  }

and then i have checks for some events

  map.on('pm:create', function (e) {
    alert('something is created');
  });

  map.on('pm:edit', function (e) {
    alert('something is created');
  });

  map.on('pm:remove', function (e) {
    alert('something is removed');
  });

events for create and remove work well, but the edit event doesn’t work.

you can see full example here

I’d be glad for any help.

How can I calculate someone’s age from a database in Google Apps Script? [duplicate]

I’ve been trying to calculate the date of birth from Google Apps Script with a Google Sheets database for a few days. The idea was the following:

  1. The users respond to a form

  2. My script collects their answers and generates an individual document for each one (based on a template) with their data

var date= new Date();
var month= date.getMonth() + 1;
var day= date.getDate();
var year = date.getFullYear();
var today= day + "/" + month+ "/" + year 

const searchTextE = "<<age>>";
const replaceTextE = Math.round((parseInt(today) - parseInt(hojaActual.getRange("with it's located the birth
date").getValue()))/365.3);

I also tried entering the date in date format (the option that the form itself gives you), but it came out with Central European time, and I only wanted it to tell me the date in this format dd/mm/yyyy, wich with the text format has been possible.

So, once the date of birth was entered (in text format) my idea was that the age could be calculated automatically (without having to ask the users) with my code, but when I look at the cell in the individual document I only see a 0.

Issue with Updating User: Uncaught SyntaxError: Unexpected token ‘<' in JSON Response

I’m encountering a persistent issue when trying to update a user profile in my PHP application. Every time I submit the modifications, I get the following error in the browser’s console:

Uncaught SyntaxError: Unexpected token '<', "<br />
<b>"... is not valid JSON
    at JSON.parse (<anonymous>)
    at Object.success (compte.php:773:38)
    at c (jquery-3.5.1.min.js:2:28294)
    at Object.fireWith [as resolveWith] (jquery-3.5.1.min.js:2:29039)
    at l (jquery-3.5.1.min.js:2:79800)
    at XMLHttpRequest.<anonymous> (jquery-3.5.1.min.js:2:82254)
compte.php:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received

I attempted to fix this by ensuring the PHP code always returns a JSON response. Here’s a snippet of the PHP code I used for updating the user profile:

// PHP code for handling user update
if ($action == 'update' && !$upload_error) {
    $user_id = validate_input($_POST['user_id'] ?? '');
    $sql = "UPDATE users SET civilite = ?, nom = ?, prenom = ?, fonction = ?, telephone = ?, email = ?, societe = ?, activite = ?, siret = ?, adresse = ?, cp = ?, ville = ?, kbis = ?, rc_pro = ?, garantie_decennale = ?, presentation = ?, profile_picture = ?, gallery_pictures = ?, video_url = ?, video = ?, website_url = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ssssssssssssssssssssi", $civilite, $nom, $prenom, $fonction, $telephone, $email, $societe, $activite, $siret, $adresse, $cp, $ville, $kbis, $rc_pro, $garantie_decennale, $presentation, $profile_picture, $gallery_pictures_json, $video_url, $video, $website_url, $user_id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => "Profile updated successfully."]);
        } else {
            echo json_encode(['success' => false, 'message' => "Error updating profile: " . $stmt->error]);
        }
        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => "Error preparing statement: " . $conn->error]);
    }
    exit();
}
  1. Added JSON Content-Type Header:

    • To further ensure that the response is interpreted as JSON, I added header('Content-Type: application/json'); at the beginning of the PHP response block. Unfortunately, this didn’t resolve the issue.
  2. Checked for Hidden HTML Errors:

    • I also reviewed the server logs and tried to identify if there were any hidden PHP errors (e.g., warnings or notices) that might be causing the HTML content to be sent back instead of JSON. Despite cleaning up the code, the issue persists.
  3. AJAX Call with Error Handling:

    • On the client side, I tried to improve the error handling in the AJAX call to catch any non-JSON responses. Here’s the relevant part of my AJAX call:
$.ajax({
    url: 'compte.php',
    method: 'POST',
    data: { /* your data */ },
    success: function(response) {
        try {
            var jsonResponse = JSON.parse(response);
            // Handle the JSON response
        } catch (e) {
            console.error('Invalid JSON response', e);
        }
    }
});

Despite these efforts, I still encounter the SyntaxError: Unexpected token '<' when the response is parsed in JavaScript. This suggests that HTML content (likely an error message) is being returned instead of the expected JSON.

Would adding header(‘Content-Type: application/json’); before returning the JSON response in the PHP code be helpful?

Are there any other suggestions to ensure the response is always valid JSON?

If anyone has faced a similar issue, how did you resolve it?

Thank you in advance for your help!

How to use .querySelectorAll for items that were created with .insertAdjacentHTML

I’m building a fictional webshop for plants and currently I’m working on filtering them combining different options (light demand, water demand, toxic etc.).

Using a separate JSON file, I’m creating cards based on the data after the JSON file was fetched:

getPlants().then((data) => {
  data.forEach((data) => {
    plantcards.insertAdjacentHTML(
      "afterbegin",
      `<article class="plantcard ${getPlantLight(data.Light)} ${getPlantWater(
        data.WaterDemand
      )}wasser ${getPlantToxic(data.Toxic)}">
        <div class="article-wrapper">
          <figure>
            <img src="../images/plant_types/${data.Image}" alt="${data.Name}" />
          </figure>
          <div class="article-body">
            <h2>${data.Name}</h2>
            <h3>${data.NameLatin}</h3>
            <p>
               Standort: ${getPlantLight(data.Light)}<br/>
               Wasserbedarf: ${getPlantWater(data.WaterDemand)}<br/>
               Schwierigkeitsgrad: ${getPlantMaintenance(data.Maintenance)}<br/>
               Giftig: ${getPlantToxic(data.Toxic)}<br/>
            </p>
            <a href="#" class="read-more">
              Read more <span class="sr-only">about this is some title</span>
              <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd" />
              </svg>
            </a>
          </div>
        </div>
      </article>`
    );
  });
});

Then I want to select all elements with the class “plantcard” so that I can hide/unhide the filtered options:
let allPlantcards = Array.from(document.querySelectorAll(".plantcard"));

I always get an empty array with a length of 0, I guess because allPlantcards is created before or while the cards are loaded. I googled a lot and I can’t find a solution for this.

I also tried to place let allPlantcards = Array.from(document.querySelectorAll(".plantcard")); within other functions but then I can’t use them outside of the function, right?

Is it a good practice to serve client-side validation rules through API [closed]

I’m developing a React application that includes multiple forms with inputs where validation rules (like min and max values) can vary depending on certain parameters. For instance, an input might accept values in the range [0, 5], but this range can differ based on the type property of a data object.

The application server already has a dataset of validation rules for each variation of form inputs.

My question is: Would it be a better practice to serve these min and max values from the server through an API endpoint rather than hardcoding them directly in each component?

Here’s a simplified version of my current implementation:

export function Component({ obj }) {
  
  const maxValue = {
   "TYPE_1": 5,
   "TYPE_2": 10,
   "TYPE_3": 15
  };
  
  return (
        <FloatInput
           label="Component label"
           max={maxValue[obj.type]}
           min={0}
           name="Float input"
        />
  );
}

Considerations:

  • The rules may change over time, and I want to ensure they remain consistent across the application.
  • I’m looking to maintain best practices in terms of scalability, maintainability, and performance.
  • Would fetching these validation rules from an API be the recommended approach, or are there downsides to this method that I should consider?