Access to fetch from API has been blocked by CORS policy

I want to fetch some data from an API. But CORS policy is blocking the access for fetching

  const fetchApi = async () => {
    const result = await fetch('https://api.themoviedb.org/3/discover/movie?',
    {
      method: "GET",
      headers: {
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "*",
        'Access-Control-Allow-Credentials': true,
        accept: 'application/json',
        Authorization: 'Bearer API_KEY',
        'callback' : 'test'
      }
    })
  }
  useEffect(() => { fetchApi() }, [])

Error screenshot

As of my limited knowledge, header data is not getting passed.

I tried two things :

  1. Instead of passing API key through header, I added api key with url. It gave result. But my requirement is to pass API key via header.

2.Tried adding access-controls in header. Still the error remains the same

IOS or web development or cyber security engineer?

i want to get in programming, and currently i work in goverment bank and i’m really not happy with the salary and the environment i’m in, in term of skills development and also financially.

Please help me to decide which path should i choose.

My prior knowledge and skills :

  • i have bechalore in electronics communication engineering
  • i have a knowledge of administration and installing windows servers
  • basic knowledge of linux servers and OS
  • i have a knowledge of installing and administration of exchange servers
  • Oracle SQL and bulding reports using Jasper
  • Basic knowledge of networking (worked with cisco switches and routers)
  • Business knoledge of banking sector and it’s operations
  • basic knowledge of HTML and CSS
  • i took courses in ISO & ITIL 4
  • IT support skills

My goal:

  • To be able to have a remote job and relocate to another country
  • i love tech in general, and i don’t mind working in either IOS dev or web dev or cybersecurity
  • i’d love to have a passsive income on the side, like my own project that could lead to a company to work for my self as my full time job.
  • i search for good income as well, good salary.

i need expert help to decide

Trying to skip over objects that are in an array when filtering

I am trying to maintain objects that are “active” ie stored in global state when a filter is applied (currently the disappear when the filter is set). To do this I am trying to get the array of objects from state with a selector and then skip over any of the objects in that array where there is a matching id when filtering occurs. Unfortunately this is not working:

  const activeCards = selectors.getActiveCards();


 {selected === "Morphology"
          ? // Filters through the 'morphemeData' array
            morphemeData
              .filter(
                (m: Affix) =>
                  // Returns items from the array where either no search term is present or the start of the affix name matches the search term (case insensitive)
                  (!searchTerm ||
                    m.affix_name
                      .toLowerCase()
                      .startsWith(searchTerm.toLowerCase())) &&
                  (filter === "all" ||
                    (m.affix_position === filter &&
                      !activeCards.morphemes.some(
                        (activeCard) => activeCard.id === m.id
                      )))
              )
              .map((m: Affix) => (
                <MorphemeCard
                  key={m.id}
                  morpheme={m}
                  position={selectors.getMorphemePosition(m)}
                  onMoved={(position) => actions.setMorpheme(m, position)}
                  onReset={() => actions.resetMorpheme(m)}
                />
              ))

Here’s how the activeCards data looks

morphemes:[
{id: 6, affix_name: 'es', affix_position: 'suffix', affix_description: 'Th -es suffix means there is more than one (plural)', affix_example: 'The buses are all running late', …},
{id: 8, affix_name: 'ade', affix_position: 'suffix', affix_description: 'The suffix -ade is used to indicate a fruit (often citrus) flavoured drink.', affix_example: 'This lemonade is delicious', …},
{id: 9, affix_name: 'age', affix_position: 'suffix', affix_description: 'The suffix -age means a collection of things', affix_example: 'We are taking alot of baggage on our trip.', …}
]

You may need an appropriate loader to handle this file type in JavaScript

I’m trying to import a React components library that I’ve created and published on npm. Although, when importing the header component I get the following error:

Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export default function Accordion(props) {
|   return (
>     <details className={styles.accordion}>
|       <summary className={styles.accordion__summary}>{props.title}</summary>
|       <div className={styles.accordion__content}>{props.children}</div>

Import trace for requested module:
./node_modules/safetyhub-components/src/components/accordion/Accordion.js
./node_modules/safetyhub-components/index.js
./src/pages/layout.js

Accordion component

import styles from "./Accordion.module.scss";
import "../../index.scss";

export default function Accordion(props) {
  return (
    <details className={styles.accordion}>
      <summary className={styles.accordion__summary}>{props.title}</summary>
      <div className={styles.accordion__content}>{props.children}</div>
    </details>
  );
}

Import code

import AppHeader from "safetyhub-components";

export default function Layout({ children }) {
  return (
    <>
      <AppHeader />
      <main>{children}</main>
    </>
  );
}

Identify values of row on Datatables javascript PHP

I have problem to classify row from SQL which empty or not,
Here the sample of SQL data :

   ============================    
   |id | name      | notadp   |   
   ============================    
   |1  | johny     | e12sda3rd|    
   |2  | yes       |          |     
   |3  | papa      |          |   
   ============================ 

I want to classify using column notadp which is empty and will not show the button.

I tried with this code :

  {
      "data" : "notadp",
      "orderable": false,
      "className" : "text-left",
      "render": function(data, type, row, meta){
         globalData=row.notadp;
         if(globalData.length > 1){
         return '<i class="fa fa-file"></i>', 'class="btn btn-xs btn-success" data-toggle="tooltip" title="Nota Booking Fee"'
         } else {
         }
      }
  },

But the result for all rows shows the button. It should be just row 1. Is there any suggestion for my code above?

Thank you master

Is the code for elements in html changed, none of my code seems to be working? I’m trying to draw a line

I keep encountering errors when trying to draw anything in html elements. I’ve gone onto reddit, W3 Schools, and about 30 other tutorials. I asked ChatGPT, and it gave me the same code. Nothing is off in the dev console either. Please help.
Here is the link to my github page… https://finnyjokes.github.io/JavascriptGames/

I tried changing variables, even going as far as to remove my css. I was originally using external JS, and am now using in-line JS, which I hate.
Here is the full code.

<html>
  <head>
    <title>JS GAME</title>
    <link rel="stylesheet" href="style.css">
    <style>
      body {
        background:black;
        text-align:center;
        color:white;
      }
      canvas {
        background-color:darkgray;
      }
    </style>
  </head>
  <body>
    <h1>JSGAME</h1>
    <canvas id="myCanvas">
      <script src="mainGame.js">
          var c = document.getElementById("myCanvas");
          var ctx = c.getContext("2d");
          ctx.moveTo(0, 0);
          ctx.lineTo(200, 100);
          ctx.stroke();
      </script>
    </canvas>
  </body>
</html>

It keeps coming up with the canvas showing, and noting else in the canvas.
I’ve been doing web development for 10ish years, but I still can’t figure this out. Please help.

How to find links children of any level

I have the following piece of html inside a page I loaded using puppeteer and I’m trying to get all the child links (not just direct children, child as at any level).

<ul class="ptf">
    <li class="pti">
        <div data-testid="pagetree-item-expander" class="pe" role="button" tabindex="0" aria-expanded="false"></div>
       <a href="/jsw/docs/start” data-testid="atlas_link">kl</a>
       <ul class="ptf" style="display:none">
            <li class="pti">
                <a href="/jsw/docs/what/" data-testid="atlas_link">ij</a>
            </li>
            <li class="pti">
                <a href="/jsw/docs/where/" data-testid="atlas_link">gh</a>
            </li>
            <li class="pti">
                <a href="/jsw/docs/common/" data-testid="atlas_link">ef</a>
            </li>

        </ul>
     <li class="pti">
         <div data-testid="pagetree-item-expander" class="pe" role="button" tabindex="0" aria-expanded="false"></div>
       <a href="/jsw/docs/ge/" data-testid="atlas_link">cd</a>
       <ul class="ptf" style="display:none">
            <li class="pti">
                <a href="/jsw/docs/wha/" data-testid="atlas_link">ab</a>
            </li>
      </li>
</ul>

I tried the following but it’s not listing down any children. What am I doing wrong?

const links = await page.$x("//*[@id="root"]/div[2]/div/li[5]/ul//a");
  
  for (let i = 0; i < links.length; i++) {
    
    const textContent = await links[i].getProperty("href");
    const srcText = await textContent.jsonValue();
    console.log(srcText);
  }

Error while interpolating way points with turf.js

enter image description here

I’m working with leaflet, node and turf.js for gis calculations. I’m trying to plot a road on a map with points every 200 meters.

On the client page (inside the script tag) I have the following:

  (async function buildMap(params) {
    const o = await getGeoJSONArr();
    console.log('getGeoJSONArr ',o);
    const polyline1 = o.jsonArr;
    const centerCoords = o.reversedCoords;
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
      maxZoom: 18,
    }).addTo(mymap);

    mymap.setView(centerCoords, 13);

    console.log("polyline1 ", polyline1);

    const reversedPolyLine1 = polyline1.map((coord) => coord.reverse());

    // have to reverse openstreetmap lat/long for leaflet

    L.polyline(reversedPolyLine1, { color: "blue" }).addTo(mymap);

    var road = turf.lineString(reversedPolyLine1);

    const roadLength = turf.length(road, {
      units: "meters",
    });
    console.log("RL ", roadLength);

    let pointList = [];
    for (let distance = 0; distance < roadLength; distance += 200) {
      const point = turf.along(road, distance, { units: "meters" });
      console.log('point ',point);
      pointList.push(point.geometry.coordinates);
    }
    console.log('pointlist ',pointList);
    L.polyline(pointList, { color: 'red' }).addTo(mymap);

  })();

I’m working in arizona which has approximately (31.xx, -112.xx) latitude/longitude. You can see that the first point looks correct, but the remainder of the ‘interpolated’ points show up as:

31.x,-67.x , which is nowhere near Arizona. What am I doing wrong?

ASP.net MVC cascading dropdown not loading

We have an asp.net mvc application that uses jQuery 1.1 version and older .net framework. I updated it to use jQuery 3.6.4 from 1.12.3/jQuery Ui 1.11.1 to 1.13.2/.NetFramework from 4 to 4.6.2/Kendo version 2017 to 2020 . Most part of application works as before but cascading dropdowns are not refreshing based on selection of first dropdown. Html rendered in console seems fine with required ajax calls to load dropdown. Not sure if there is any version compatibility with components aim upgrading. I see this error in console UnCaught TypeError: n.Indexof is not a function at 1.fn.load(jquery?v=) at <anonoymouse?210:21) etc.,

javascript wrong result in division from input number fields

i have two input fields.
I have to divide one fields for the other

This is my javascript code

$("#circonferenza_vita").on("change",function(){
    var vita = $('#circonferenza_vita').val();
    var fianchi = $('#circonferenza_fianchi').val();
    alert(vita + " " + fianchi);
    var whr = (vita / fianchi);
    $('#whr').val(whr);
});

});

But when i insert the value in the input fields i have a wrong result.
For example if i insert vita 90 and fianchi 75 the result should be 0.8333 but i receive the result 1.2
Note that the alert return the correct values for vita and fianchi but the result is wrong.
Someone can help to understand and fix this issue? It is driving me crazy 🙂

Why button dont work in html and javascript?

Why increment and decrement buttons dont work, they was working well but when I add type="button" stop working.

html

<form th:action="@{/home}" method="post" style="margin-top: 10px; display: block">
      <div style="margin-bottom: 10px; margin-top: 10px;">
          <button type="button" name="decrement"  onclick="decrement()" style="display: inline; margin-right: 5px; width: 20px" id="decrement">-</button>
          <output style="display: inline" name="quantity" id="quantity">0</output>
          <button type="button" name="increment" onclick="increment()" style="display: inline; margin-left: 5px; width: 20px" id="increment">+</button>
          <input type="hidden" name="itemId" th:value="${item.getItem_id()}"/>
          <button type="submit" name="addToCart" class="addToCart-btn">Add to cart</button>
       </div>
</form>

javascript

function increment(button) {
    var counter = button.parentNode.querySelector("output");
    counter.textContent++;
    updateAddToCartButton(button)
}

function decrement(button) {
    var counter = button.parentNode.querySelector("output");
    if (counter.textContent > 0) {
        counter.textContent--;
        updateAddToCartButton(button)
    }
}

function updateAddToCartButton(button) {
    var quantity = parseInt(button.parentNode.querySelector("#quantity").innerText);
    var submitButton = button.parentNode.querySelector(".addToCart-btn");

    if (quantity > 0) {
        submitButton.style.display = "inline";
    } else {
        submitButton.style.display = "none";
    }
}

HTTP GET Request and Response

I’m trying to request some data from a webpage I have, through a HTTP GET request.

I only want the response to return certain data, that I pass as a URL paramater.

How can I do this?

Example: I only want the response to include Object B and not the rest of the data.

Webpage:

Object A
Object B
Object C

I tried adding a script on the webpage to filter the data but the HTTP request doesn’t wait for it to finish. It returns all the objects and the script in the response.