why i don’t able to get value of a element of html using javascript

here is the html content

<div id="result-box" class="col-5">
                <h3 class="result" id="name" >Name: --- </h3>
                <h3 class="result" id="age">Age: ---</h3>
                <h3 class="result" id="class">Class: --- </h3>
                <h3 class="result" id="skill">Skill:--- </h3>
                <h3 class="result" id="gen">Gender: --- </h3>
                <h3 class="result" id="perform">Perfomance: --- </h3>
            </div>

here is the js code You tell me what is the error/mistake in this

let name = document.getElementById('name').value;
let age = document.getElementById('age').value;
let class = document.getElementById('class').value;
let skil = document.getElementById('skill').value;
let gen = document.getElementById('gen').value;
let perform = document.getElementById('perform').value;

let name = document.getElementById('name').value
console.log(name)


In console panel it says undefined what is reason behind this, please guide me

can anyone figure out why javascript is not accepting the #color plz?

function goToSlide3(){
    if(advanced.style.borderColor==="#FF00B8" ||      
    pro.style.borderColor==="#483EFF" || arcade.style.borderColor==="#FF8A00"){
}

i’m trying that if the pro.style.borderColor===”#FF00B8″ or(||) arcade.style.borderColor===”#FF8A00″) then goToNext slide but javascript cant recognize the #colors but it recognize the color ex. arcade.style.borderColor===”red” then it accept it plz give any solution?

convert markdown format to image in html

i want to change markdown format of image to html.

But no success.

My html:

<label class="control-label abc-control-label"  id="image2">![ ](https://i.imgur.com/ZE8HMqh.png)</label> 
<br> 
<label class="control-label abc-control-label" id="image1">![ ](https://i.imgur.com/P92SWSj.png)</label>

my javascript:

$image_markdown = $(this).text() $image_format =
$image_markdown.match(/![.*?]((.*?))/) $new_image = '<img src="' +
$image_format + '" style="width:200px">' $(this).html($new_image);

My demo link : https://jsfiddle.net/bvotcode/6y0gupjq/8/

Thank you

Why does my modal keyboard trap stop working when 2 buttons are enabled?

When the modal is open, I don’t want users to be able to tab outside of it. This works while the “Agree & Download” button is disabled, but once that button becomes enabled, the keyboard trap breaks.

If I have the “Dummy Button” in the modal (currently commented out), everything works fine. I would like to make it work without the dummy button, though.

I think it’s a problem with the array of focusable children not updating when the Agree & Download button is enabled, but I can’t figure out how to fix that, either.

Thanks in advance for any help.

HTML:

    <div 
      class='modal' 
      role='dialog' 
      aria-labelledby='modal__title' 
      aria-describedby='modal__title' 
      tabindex='0' 
      data-modal='open'
    >
      <div class='modal__content'>
        <button class='modal__close-button' aria-label="Close modal" data-modal-close-button tabindex="0">
        </button> 
        
        <div id='modal__title'>Read the End-User License Agreement (EULA) to download the SDK file.</div>
        <div id="ScrollBox">
          <h1 class="Legal__H1">SOFTWARE LICENSE AGREEMENT</h1>
          <p>YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT BEFORE PROCEEDING. BY SELECTING “I AGREE” YOU ARE AGREEING TO BECOME BOUND BY THE TERMS OF THIS SOFTWARE LICENSE AGREEMENT.</p>
          <p>YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT BEFORE PROCEEDING. BY SELECTING “I AGREE” YOU ARE AGREEING TO BECOME BOUND BY THE TERMS OF THIS SOFTWARE LICENSE AGREEMENT.</p>
          <p>YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT BEFORE PROCEEDING. BY SELECTING “I AGREE” YOU ARE AGREEING TO BECOME BOUND BY THE TERMS OF THIS SOFTWARE LICENSE AGREEMENT.</p>
          <p>YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT BEFORE PROCEEDING. BY SELECTING “I AGREE” YOU ARE AGREEING TO BECOME BOUND BY THE TERMS OF THIS SOFTWARE LICENSE AGREEMENT.</p>
          <p>YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT BEFORE PROCEEDING. BY SELECTING “I AGREE” YOU ARE AGREEING TO BECOME BOUND BY THE TERMS OF THIS SOFTWARE LICENSE AGREEMENT.</p>
          <p>YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT BEFORE PROCEEDING. BY SELECTING “I AGREE” YOU ARE AGREEING TO BECOME BOUND BY THE TERMS OF THIS SOFTWARE LICENSE AGREEMENT.</p>
        </div>

        <button role="button" id="AgreeAndDownload" disabled>Agree & download</button>

        <!--<button role="button">Dummy Button</button>-->
      </div>
    </div>
    
    <button role="button" class="modal__open-button" data-modal-trigger='open'>Download</button>

Javascript:

    <script>
      'use strict';

      // create a modal object, set the target element, and create a list of focusable elements
      var modal = modal || {
        set: Array.from(document.querySelectorAll('[data-modal]')),
        openTriggers: Array.from(document.querySelectorAll('[data-modal-trigger]')),
        closeTriggers: Array.from(document.querySelectorAll('[data-modal-close-button]')),
        focusable: 'a[href], area[href], input, select:not([disabled]), textarea:not([disabled]), button:not([disabled]), object, embed, *[tabindex], *[contenteditable]',
        focused: ''
      };

      // initialize the modal, find the focusable children elements and set up the click handlers
      modal.init = function() {
        modal.set.forEach(modal => {
          modal.setAttribute('aria-hidden', 'true'); 
        });
        modal.openTriggers.forEach(trigger => {
          trigger.addEventListener('click', function(e) {
            e.preventDefault();
            let name = this.dataset.modalTrigger;
            modal.el = modal.set.find(function(value) {
              return value.dataset.modal == name;
            });
            modal.show();
          })
        });
        modal.closeTriggers.forEach(trigger => {
          trigger.addEventListener('click', function(e) {
            e.preventDefault();
            modal.hide();
          })
        });
      };

      // capture the current focused element so that you can set focus back to it when you close the modal
      // add a class to the body to style for modal
      // hide the rest of the content
      // set aria hidden to false
      // add class to modal
      // set focus to first focusable element from list created in init function
      modal.show = function() {
        document.body.classList.add('has-modal');
        document.querySelector('.modal__open-button').setAttribute('aria-hidden', true)
        modal.focused = document.activeElement;
        modal.el.setAttribute('aria-hidden', 'false'); 
        modal.el.classList.add('modal--show');
        // todo: filter this to only visible children
        modal.focusableChildren = Array.from(modal.el.querySelectorAll(modal.focusable));
        modal.focusableChildren[0].focus();
        modal.el.onkeydown = function(e) {
          modal.trap(e);
        }
        console.log(modal.focusableChildren.length + " focusable elements");
      };

      // remove body classes that were added
      // reset aria hidden values from container
      // reset aria hidden values on modal
      // remove show class from modal
      // set focus to previously focused element
      modal.hide = function() {
        document.body.classList.remove('has-modal');
        document.querySelector('.modal__open-button').setAttribute('aria-hidden', false)
        modal.el.setAttribute('aria-hidden', 'true');
        modal.el.classList.remove('modal--show');
        modal.focused.focus();
      };

      // if key is esc, close the modal
      // if key is tab
      // get the current focus
      // get the total focusable items to filter through them later
      // get the index from the focusable items list of the current focused item
      // if key is shift tab (backwards) and you're at the first focusable item, set focus to the last focusable item
      // if not shift tab and the current focused item is the last item, set focus to the first focusable item
      modal.trap = function(e) {
        console.log("trap");
        if (e.which == 27) {
          modal.hide();
        } 
        if (e.which == 9) {
          let currentFocus = document.activeElement;
          let totalOfFocusable = modal.focusableChildren.length;
          let focusedIndex = modal.focusableChildren.indexOf(currentFocus);
          if (e.shiftKey) {
            if (focusedIndex === 0) {
              e.preventDefault();
              modal.focusableChildren[totalOfFocusable].focus();
            }
          } else {
            if (focusedIndex === totalOfFocusable - 1) {
              e.preventDefault();
              modal.focusableChildren[0].focus();
            }
          }
        }
      };
      
      // Disable download button until EULA has been scrolled completely
      function setupScrollBox() {
        const ScrollBox = document.getElementById('ScrollBox');
        const AgreeAndDownload = document.getElementById('AgreeAndDownload');
        ScrollBox.addEventListener('scroll', function() {
            if (ScrollBox.scrollTop + ScrollBox.clientHeight >= ScrollBox.scrollHeight) {
              AgreeAndDownload.disabled = false;
              AgreeAndDownload.focus();
              console.log("you did it!");
            } else {
              console.log("not yet!");
            }
            console.log(modal.focusableChildren.length + " focusable elements");
          }
        );
      };

      modal.init();
      setupScrollBox();

    </script>

Prevent Svelte from adding random classes

I have a shadow-root component and I simply don’t want svelte-kit to add those random classes to that specific element or its child elements. It would be nice if there was something in the settings like: document.getElementById("<id>").cssHash == false

Or any possible hacks to achieve this?

enter image description here

Request Format from Javascript to Postman

For start, I am new to programming, so not realy sure how to ask this correctly.

I am working on an integration between my company’s pbx and a external CRM. I have the CRM documentation (that is really laking) and it presents the request in this format:

<script type="text/javascript">
    .callMethod(
        "crm.lead.list", 
            { 
                order: { "STATUS_ID": "ASC" },
                filter: { ">OPPORTUNITY": 0, "!STATUS_ID": "CONVERTED" },
                select: [ "ID", "TITLE", "STATUS_ID", "OPPORTUNITY", "CURRENCY_ID" ]
            } 

How do I set a request on the format used by Postman to try some queries?

I tried /crm.lead.list?$filter={“PHONE”:”333444″} and several variations on that, but can’t make it work. It always bring me the full lead list and ignores the filters.

Is there any way to set border radius only for the top of stacked column chart in angular?

I was trying to modify solution from there http://jsfiddle.net/BlackLabel/vd2Ly9eh/ in the way, that jquery won’t be used but I haven’t succeed. Also I tried to use highcharts-rounded-corners plugin, but my angular app doesn’t have opportunity to parse import of js files (it needs file with d.ts extension).

JQuery:

 $(function() {
  Highcharts.wrap(Highcharts.seriesTypes.column.prototype, 'translate', function(proceed) {
    proceed.apply(this, [].slice.call(arguments, 1));
    var series = this,
      cpw = 0.166,
      shapeArgs,
      x, y, h, w;

    Highcharts.each(series.points, function(point) {
      shapeArgs = point.shapeArgs;
      x = shapeArgs.x;
      y = shapeArgs.y;
      h = shapeArgs.height;
      w = shapeArgs.width;

      point.shapeType = 'path';
      if (point.negative) {
        point.shapeArgs = {
          d: [
            'M', x, y,
            'L', x, y + h - w / 2,
            'C', x, y + h + w / 5, x + w, y + h + w / 5, x + w, y + h - w / 2, 'L', x + w, y,
            'L', x, y
          ]
        };
      } else {
        point.shapeArgs = {
          d: [
            'M', x, y + w / 2,
            'L', x, y + h,
            'L', x + w, y + h,
            'L', x + w, y + w / 2,
            'C', x + w, y - w / 5, x, y - w / 5, x, y + w / 2
          ]
        };
      }
    });
  });


  $('#container').highcharts({
    chart: {
      type: 'column'
    },
    series: [{
      data: [2, 3, -2, 3, 2]
    }]
  });
});

My variant (https://jsfiddle.net/7u4vjre0/12/):

Highcharts.chart('container', {
    chart: {
        type: 'column',
        events: {
            load: function () {
                const chart = this;
                chart.series.forEach((item, itemIndex) => {
                    item.points.forEach((point, pointIndex) => {
                        const {x, y, height, width} = point.shapeArgs;
                        this.series[itemIndex].points[pointIndex].shapeType = "path";
                        if (point.negative) {
                            this.series[itemIndex].points[pointIndex].shapeArgs = {
                                d: [
                                    "M",
                                    x,
                                    y,
                                    "L",
                                    x,
                                    y + height - width / 2,
                                    "C",
                                    x,
                                    y + height + width / 5,
                                    x + width,
                                    y + height + width / 5,
                                    x + width,
                                    y + height - width / 2,
                                    "L",
                                    x + width,
                                    y,
                                    "L",
                                    x,
                                    y,
                                ],
                            };
                        } else {
                            this.series[itemIndex].points[pointIndex].shapeArgs = {
                                d: [
                                    "M",
                                    x,
                                    y + width / 2,
                                    "L",
                                    x,
                                    y + height,
                                    "L",
                                    x + width,
                                    y + height,
                                    "L",
                                    x + width,
                                    y + width / 2,
                                    "C",
                                    x + width,
                                    y - width / 5,
                                    x,
                                    y - width / 5,
                                    x,
                                    y + width / 2,
                                ],
                            };
                        }
                    });
                });
            },
        },
    },
    title: {
        text: '',
    },
    xAxis: {
        categories: ['Arsenal', 'Chelsea', 'Liverpool']
    },
    yAxis: {
        min: 0,
        title: {
            text: ''
        },
    },
    plotOptions: {
        column: {
            stacking: 'normal',
            dataLabels: {
                enabled: true
            }
        }
    },
    series: [{
        name: 'Test 1',
        data: [3, 5, 1]
    }, {
        name: 'Test 2',
        data: [14, 8, 8]
    }, {
        name: 'Test 3',
        data: [0, 2, 6]
    }]
});

JavaScript/JQuery – Object property values are changing when looping through them

We are attempting to create a routing (TSP) algorithm that loops through a data structure that holds our vehicles and our trip information.

It all starts with an ASYNC function called acquireData that makes a $.getJSON call to our own API which returns a large object structure of all our vans and trips and all (too much) the information. This async function loops through the API object return and builds a brand new object with a LOT less data…

It returns the new object as a result.

At the bottom we call the async function and then we want to do all the TSP solving in the .then().

Here is where we start to run into the issue.

console.log(data)

In the .then() we log “data” (which is the returned object from the async function acquireData()) and everything looks good. The image aboce is console.log(data.trucks). You can see all the avilableAt properties have a different date/time except for the ones who do not have a trip. This is the way its supposed to be. All is good up to this point, the data is exactly as we want it.

Now……..

When we attempt to loop through this data.trucks, the availableAt properties go haywire. $.each(data.trucks, function(d, j){
console.log(d, j.availableAt)})

Once we loop through this and display the availableAt properties, they all get the same date/time. Compare the two picture’s and look at “Med 2” you’ll see the difference.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <title>Document</title>
</head>
<body>

  <script>

    function createDateObject(dateString, militaryTime) {
      if (typeof dateString === "boolean" || typeof militaryTime === "boolean" || militaryTime == ""){
        
        return "No Date"
      } else {
        const year = parseInt(dateString.slice(0, 4));
        const month = parseInt(dateString.slice(5, 7)) - 1;
        const day = parseInt(dateString.slice(8, 10));
        const hours = parseInt(militaryTime);
        const date = new Date(year, month, day, hours);
        return date;
      }
    }

    function formatCityState(city, state) {
      const formattedCity = city.replace(/ /g, '+');
      const formattedState = state.toUpperCase();
      return `${formattedCity},${formattedState}`;
    }

    function addSeconds(date, seconds) {
      var newDate = new Date(date.getTime() + seconds * 1000);
      return newDate;
    }

    function isBefore(date1, date2) {
      return date1.getTime() < date2.getTime();
    }

    function addHalfHourEvery4Hours(seconds) {
      var hours = seconds / 3600; // convert to hours
      var timeSlots = Math.floor(hours / 4); // calculate number of 4-hour time slots
      var extraHours = timeSlots * 0.5; // calculate extra half-hours
      var newHours = hours + extraHours; // add extra half-hours to original hours
      var newSeconds = newHours * 3600; // convert back to seconds
      return newSeconds;
    }

    const callGoogle = async(origin, destination) => {
      const params = encodeURIComponent('&origins=' + origin + '&destinations=' + destination);
      const grabData = await $.getJSON('no-cors.php?url=https://maps.googleapis.com/maps/api/distancematrix/json?' + params + '&key=xxxxxxx')
      return grabData;
      }

    async function acquireData() {
    const data = await new Promise((resolve, reject) => {
      $.getJSON('https://xxxxxxxxxx/xxxxx.php', function(data) {
      const newData = {
        // employees: {},
        trucks: {},
        trips: [],
        trips_unscheduled: []
      };
      $.each(data.trucks, function(j, k) {
        const truckObj = {
          trips: [],
          standing_location: k.name_value_list.location_c.value
        };
        if (j.includes('Med') || j == "") {
          if (k.trips) {
            for (let i = 0; i < k.trips.length; i++) {
              const tripDate = new Date(k.trips[i].name_value_list.transport_date_2_c.value);
              const now = new Date();
              const timeDiff = tripDate - now;
              const diffInHours = timeDiff / (1000 * 3600);
              const tripObj = {
                trip_id: k.trips[i].name_value_list.trip_id_c.value,
                dropoff_location: formatCityState(k.trips[i].name_value_list.arrival_city_c.value, k.trips[i].name_value_list.arrival_state_c.value),
                pickup_location: formatCityState(k.trips[i].name_value_list.departure_city_c.value, k.trips[i].name_value_list.deprature_state_c.value),
                pickup_time: createDateObject(k.trips[i].name_value_list.transport_date_2_c.value, k.trips[i].name_value_list.pick_up_time_c.value, k.trips[i].name_value_list.trip_id_c.value)
              };

              if (diffInHours > 48 && tripObj.pickup_time != "No Date") {
                newData.trips.push(tripObj);
              } else if (diffInHours < -45000 || tripObj.pickup_time == "No Date") {
                newData.trips_unscheduled.push(tripObj)
              } else {
                truckObj.trips.push(tripObj);
              }
            }
            //Generate availableAt for trucks with trips.
            if (truckObj.trips.length > 0) {
              var Corndogs = callGoogle(truckObj.trips[truckObj.trips.length - 1].pickup_location, truckObj.trips[truckObj.trips.length - 1].dropoff_location)
              .then((data) => {
                truckObj.availableAt =  addSeconds(truckObj.trips[truckObj.trips.length - 1].pickup_time ,addHalfHourEvery4Hours(data.rows[0].elements[0].duration.value))
                newData.trucks[j] = truckObj;
              })
            } 
          }
          //Generate availableAt for trucks with no trips. 
          let t = new Date()
          let tomorrow = new Date(t.setHours(t.getHours() + 24))
          truckObj.availableAt = tomorrow
          newData.trucks[j] = truckObj;
        }
      });
      resolve(newData);
    });
  });
  return data;
}

//now that we have our data built out the way we want it, we can loop through it and find the best truck for each trip.



//We will start by looping through each trip. 
  //Loop through each truck
    //if truck availableAt is before pickup time that means this truck is a possibility for current trip
      //calculate if the truck can make it to the trip pickup location in time
        //if it can lets save the travel time and distance in a variable as well as the good truck
          //loop through trips again and if there is a trip that is closer and has less sitting time lets replace 
          //continue looping through all the trucks ; everytime we find a truck that can make the trip but is less travel time and distance , save these details to the variable.
           
          
//Loop through each truck
  //Loop through each trip
    //if truck availableAt is before the tripPickUpTime then lets dive further
      //calculate travel time and distance from trucks drop off and avaialbleAt
        //if truck can make it in time
          //lets save that distance and time spent sitting into a variable and save that truck 
            //continue to compare it to other trucks nd if we find a lower distance/time
              //once we have looked through all the trucks  



acquireData().then((data) => {

  console.log(data)

  $.each(data.trucks, function(d, j){
    console.log(d, j.availableAt)
  })
  // console.log(data.trucks)

}).catch((error) => {
  console.error(error);
});



  </script>
  
</body>
</html>

How to use a mixin in pug.compile()

I want do something like this:

mixin table_row(event)
    tr 
        td=event.name
        td=event.type
        td=event.time
        td=event.venue
        td
            +dropdown(event.id)

script.
    const setEvents = (events) => {
        let tbody = document.getElementById('events-tbody')

        const compile = pug.compile(
            `each event in events` +'n'+
            `   tr` +'n'+
            `       +table_row(event)`
        )

        tbody.innerHTML = compile({events})
    }

On a button click, I am calling an API that fetches events. I want to display these events in a table using table_row mixin that I have already defined in the .pug file.

Right now this code gives an error that table_row is not defined. Is there a way for me to pass this mixin in the pug.compile() function?

Reference:
https://pugjs.org/api/reference.html#pugcompilesource-options

CORS issues on reactjs app but not on flutter macos or mobile application

I’m new to reactjs and I’m trying to get an RSS feed using fetch a url. The get request works fine on the mobile app but not on the web. It generates a CORS error. Because Google owns the server, I can’t modify it to allow local hosts, so the solution must be implemented on the client side. I’m sure this has already been resolved. Could someone please explain two things to me:

  1. How to get a URL from the web.
  2. Why mobile get requests work on the same url without issues but not on the web?

Code for your reference

  const url = "https://news.google.com/rss/topics/" +
  "CAAqJQgKIh9DQkFTRVFvSUwyMHZNRE55YXpBU0JXVnVMVWRDS0FBUAE" +
  "?hl=en-IN&gl=IN&ceid=IN%3Aen"

  const response = await fetch(url);

scope access function external parameters parameters using scoping js?

Is there a way to get index and step parameters using scoping ? Using vue/alpinejs I’m trying to do an infinite scroll using this function. But I have the error vm.getAllProducts is not a function.
https://codesandbox.io/s/onscroll-izfjoc?file=/index.html

// script.js
people: [],
index: 0,
step: 5,

goScroll: function () {
  const vm = this; // save the instance to a variable
  window.document
    .querySelector(".content__mid-wrapper")
    .addEventListener("scroll", function () {
      const {
        scrollTop,
        scrollHeight,
        clientHeight
      } = window.document.documentElement.querySelector(
        ".content__mid-wrapper"
      );
      if (clientHeight + scrollTop >= scrollHeight) {
        vm.getAllProducts(
          (vm.index = vm.index + 5),
          (vm.step = vm.step + 5)
        ); 
      }
    });
}.bind(this)

Web Bluetooth API – Cannot write after reconnect

I have a (3rd party) native android app which sends data to a sports scoreboard via bluetooth. The scoreboard has an embedded raspberry pi where the bluetooth server is running. It seems to work fine.

I have written a React SPA/PWA for controlling the scoreboard and have been investigating the Web Bluetooth API and putting it through its paces. It is showing great promise. However, I have an issue at the moment which I can’t get to the bottom of. When my app first connects to the board, everything is hunky-dory. But then, if I disconnect, and then reconnect to the service, the bluetooth device no longer receives any data. No exception is being thrown, and the async call which is writing to the characteristic never seems to return (it appears to be running indefinitely in the background, and nothing is being written to the device). My code is below. It is only first draft. It is a react hook, whose functions are being called by various parts of the program.

The problem could well be with the server, but I just wanted a sanity check that I was handling things properly on the javascript side.

import { useEffect, useState } from 'react'

function useBluetoothScoreboard(options) {
    const [isBluetoothAvailable, setIsBluetoothAvailable] = useState(false);
    const [connectionInProgress, setConnectionInProgress] = useState(false);
    const [isConnected, setIsConnected] = useState(false);
    const [scoreboardDevice, setScoreboardDevice] = useState(null);
    const [scoreboardDeviceServer, setScoreboardDeviceServer] = useState(null);

    useEffect(() => {
        navigator.bluetooth.getAvailability()
            .then((available) => {
                setIsBluetoothAvailable(available);
            })
            .catch(() => {
                setIsBluetoothAvailable(false);
            })
    }, []);

    const disconnected = () => {
        console.log('Scoreboard is disconnected.');
    }

    const onConnect = async () => {
        try {
            if (!isConnected) {
                const connectScoreboard = async () => {
                    const options = {
                        filters: [{
                            namePrefix: 'CricNet'
                        }],
                        optionalServices: ['5a0d6a15-b664-4304-8530-3a0ec53e5bc1']
                    };         
                       
                    let device = null;
                    if (!scoreboardDevice) {
                        console.log('Pairing with bluetooth scoreboard ...');
                        device = await navigator.bluetooth.requestDevice(options);
                        device.addEventListener('gattserverdisconnected', disconnected);
                        setScoreboardDevice(device);
                    }
                    else
                    {
                        device = scoreboardDevice;
                    }

                    console.log('Connecting to bluetooth scoreboard ...');
                    const deviceServer = await device.gatt.connect();
                    setScoreboardDeviceServer(deviceServer)
                };

                setConnectionInProgress(true);
                await connectScoreboard();
                setConnectionInProgress(false);
                setIsConnected(true);
            }
        }
        catch (e) {
            console.error(e);
            setConnectionInProgress(false);
            setIsConnected(false);
        }
    };

    const onDisconnect = async () => {
        if (isConnected) {
            console.log('Disconnecting ...');
            if (scoreboardDevice.gatt.connected) {
                scoreboardDevice.gatt.disconnect();
                setScoreboardDeviceServer(null)
            }
            setIsConnected(false);
        }
    };

    const write = async (total) => {
        const buffer = new ArrayBuffer(6);
        const view = new Int16Array(buffer);
        view[0] = -1896;
        view[1] = 0;
        view[2] = total;

        if (isConnected) {
            try {
                console.log('Getting service ...');
                const service = await scoreboardDeviceServer.getPrimaryService('5a0d6a15-b664-4304-8530-3a0ec53e5bc1');
                console.log('Getting characteristic ...');
                const characteristic = await service.getCharacteristic('df531f62-fc0b-40ce-81b2-32a6262ea440');

                await characteristic.writeValueWithoutResponse(buffer);
                console.log('Should have written ...')
            }
            catch (e) {
                console.log(e)
            }
        }
    };

    return { isBluetoothAvailable, connectionInProgress, isConnected, onConnect, write, onDisconnect };
}

export default useBluetoothScoreboard;

Can’t delete a file inside S3 Bucket

I have a web app that enables users to make posts that contain files, these files are hosted using AWS S3 Buckets. (I’m using Node.js + Express)

Users can successfully post files and retrieve them, but the problem relies in deleting a file, as I get an “Access Denied” response.

Although when I created the S3 Bucket, I’ve allowed the Put, Get, and Delete permissions. And to verify that, I’ve copied the JSON from access-policy section:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::saud-demo-bucket/*"
        }
    ]
}

And to also verify that the credentials and the data passed in my node.js app are correct, I’ve placed console.log() statements to see the data passed into the getFileFromS3() function and the deleteFileFromS3() function:

Get file from S3 Bucket:

async function getFileFromS3(req) {

  console.log("REQ.QUERY.S3FILENAME IN GET FUNCTION IS:");
  console.log(req.query.s3FileName);

  const params = {
    Bucket: bucketName,
    Key: req.query.s3FileName,
  };

  const command = new GetObjectCommand(params);
  const file = await s3.send(command);

  if (file.$metadata.httpStatusCode === 200) {
    console.log("File retreived successfully!");
    return {
      success: true,
      file,
    };
  } else {
    console.log("Error retreiving file ..");
    return {
      err: true,
      file,
    };
  }
}

Delete file from S3 Bucket:

async function deleteFileFromS3(req) {
  console.log("REQ.QUERY.S3FILENAME IN DELETE FUNCTION IS:");
  console.log(req.query.s3FileName);

  const params = {
    Bucket: bucketName,
    Key: req.query.s3FileName,
  };

  const command = new DeleteObjectCommand(params);
  const result = await s3.send(command);

  if (result.$metadata.httpStatusCode === 200) {
    console.log("File deleted successfully!");
    return true;
  } else {
    console.log("Error deleting file ..");
    return false;
  }
}

Terminal Output:

[nodemon] starting `node server/server.js`
Listening ...
Connected to database successfully!
REQ.QUERY.S3FILENAME IN GET FUNCTION IS:
5e55c3065c73e828dfe2a5e1c1cf777f8ad9235b8cf3dbbcf6572f03979b32cb.docx
File retreived successfully!
REQ.QUERY.S3FILENAME IN DELETE FUNCTION IS:
5e55c3065c73e828dfe2a5e1c1cf777f8ad9235b8cf3dbbcf6572f03979b32cb.docx
(node:15800) UnhandledPromiseRejectionWarning: AccessDenied: Access Denied
    at throwDefaultError (C:UsersuserDesktopFoldersDevWebProjectsseu-studentsnode_modules@aws-sdksmithy-clientdist-cjsdefault-error-handler.js:8:22)       

I don’t have experience in s3 buckets, and I haven’t messed with something at all, I just followed a tutorial on how to do so.

So how can I tackle this issue?