How to modularize a delete route with params in Express

I am trying to hit a delete route in my Express.js app, and it is not working for some reason.

There is some issue with the way that I am setting up my router files and the request params in the listener.

I’ve tried all sorts of variations, and can’t see what I’m doing wrong. Thank you for any pointers!

the url in the request from the client is:

DELETE: “localhost:8080/api/tasks/1”

the structure of the route modules is like this:

  1. catch all of the urls that start with “/api” in the app.js file and send them to routes/index.js
  2. in routes/index, send all of the urls that start with “api/tasks” to routes/tasks.js
  3. in routes/task.js send all of the requests that have a delete verb /routes/tasks/delete.js

in routes/tasks/delete.js, there is a route:

router.delete("/:id, async (req, res, next)=>{
     ISSUE -----> this route never gets hit
})

More details:
the route files are like this:

/app.js

app.use("/api", require("./routes/index.js"));

/routes/index.js

const express = require("express");
const router = express.Router();
module.exports = router;


/**
 * @route /api/tasks
 * @verb get
 */
router.use("/tasks", require("./tasks"));


/routes/tasks/index.js

const express = require("express");
const router = express.Router();
module.exports = router;

/**
 * @route /api/tasks
 * @verb post
 */
router.post("/", require("./create"));

/**
 * @route /api/tasks
 * @verb get
 */

router.get("/", require("./read"));

/**
 * @route /api/tasks
 * @verb put
 */

router.put("/", require("./update"));

/**
 * @route /api/tasks
 * @verb delete
 */

router.delete("/", require("./delete"));



/routes/tasks/delete.js

const express = require("express");
const router = express.Router();
const db = require("../../models/db");
const { User, Task } = db.models;

module.exports = router;


router.delete("/:id", async (req, res, next) => {

  let { id } = req.params;


  // ISSUE: THIS ROUTE DOES NOT GET HIT

  console.log("hit delete route");

  try {

    res.json({ test, "hit the delete route", id });

  } catch (error) {

    next(error);

  }
});

/**

Toggle Button text After Selecting Option HTML [duplicate]

So, I’ve been trying to toggle a button text after selection an certain option.

However no matter what I try the button text doesn’t change.

I have this HTML code:

<select id="temp">
        <option value="selectOption" disabled selected>Select</option>
        <option value="farenheit">Farenheit</option>
        <option value="kelvin">Kelvin</option>
</select><br>

<button id="buttonTemp" onclick="converterTemp()">Convert</button><br>

And this is the JS code:

const slt = document.querySelector('select');

switch (slt.value) {
    case 'farenheit':
        document.getElementById('buttonTemp').innerHTML = 'Convert to Fº';
        break;

    case 'kelvin':
        document.getElementById('buttonTemp').innerHTML = 'Convert to kº';
        break;
}

It was supposed to toggle the text “Convert” to “Convert to Fº” / “Convert to Kº” on the user selection of Farenheit or Kelvin.

Could someone help me, please?

make a delete request in vue js

please how can i make a delete request in vue js

this is my script tag


  methods: {
    onDeleteAddress(id, index) {
      if (confirm("Are you sure?") === true) {
        axios
          .delete(
            `http://localhost:5000/api/addresses/${this.$route.params.id}`
          )
          .then(response => {
            console.log(response);
          })
          .catch(error => {
            console.log(error);
          });
      }
    }
  }

this is how i call my function in my vue template

 <a href="#" @click="onDeleteAddress(address._id)">Delete</a>

this what my console show me when i click onDeleteAddress(address._id) https://imagizer.imageshack.com/img922/1544/V8jGBH.jpg

this is my backend route


// DELETE delete an address
router.delete("/addresses/:id", verifyToken, async (req, res) => {
  try {
    let deletedAddress = await Address.remove({
      user: req.decoded._id,
      _id: req.params.id
    });

    if (deletedAddress) {
      res.json({
        success: true,
        message: "Address has been deleted"
      });
    }
  } catch (err) {
    res.status(500).json({
      success: false,
      message: err.message
    });
  }
});

please how can i go about this

Css Keyframe animation opacity get flashing when click on dropdown menu

After several attempts to add a simple in / out animation with opacity, I got the result I wanted. However, the animation is causing unwanted flashes.

If you switch from one item to another you will notice that the content will flash for a moment. What am I doing wrong ?

Also, is there a “cleaner” and shorter way to achieve the same effect?

var dropdownBtn = document.querySelectorAll('.menu-btn');

dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
  var menuContent = this.nextElementSibling;
  closeMenusExcept(menuContent);
  if (!menuContent.classList.contains("show")) {
      menuContent.classList.add("show");
  } else {
    menuContent.classList.add("hide");
    setTimeout(function(){
     menuContent.classList.remove("show");
     menuContent.classList.remove("hide");  
    },100)
    } 
}));

function closeMenusExcept(menuContent) {
  dropdownBtn.forEach((element) => {
    if (menuContent !== element.nextElementSibling) {
      element.nextElementSibling.classList.remove("show");
      element.nextElementSibling.classList.add("hide");
    }
  })
}
.menu-btn {
  background: #e0e0e0;
  padding: 10px;
  margin: 5px 0px 0px 0px;
}

.menu-btn:hover {
  background: #000;
  color: #fff;
}

.drop_container {
  display: none;
  background-color: #fff;
  animation:animateFromBottom 0.3s
  
}

.drop_container.show {
  display: block;
}

.drop_container.hide {
  animation:animateToBottom 0.3s;
}

.drop_container > .item {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  padding: 10px 0px 0px 0px;
}

@keyframes animateFromBottom {
    from{opacity:0} 
    to{opacity:1}
}

@keyframes animateToBottom {
  from{opacity:1} 
  to{opacity:0}
}
<div class="dropdown-menu">

<div class="menu-btn">One</div>
<div class="drop_container">
  <a class="item" href="#">Contact Us</a>
  <a class="item" href="#">Visit Us</a>
</div>

<div class="menu-btn">Two</div>
<div class="drop_container">
  <a class="item" href="#">Contact Us</a>
  <a class="item" href="#">Visit Us</a>
</div>

</div>

How to Manipulate Sets of Buttons in React with UseStates?

Hi I am new to react and trying to get buttons to light up when you press them, however they are in sets of buttons and I’d like the other buttons in the set to not also light up when one is pressed.

Currently I used UseState() and it just turns all buttons on and off. What’s the best practice work around to this, because creating 30 individual button functions does not seem practical.
Buttons

  const [ticket, setTicket]=useState(false)


  const ticketHandler = () => {
    setTicket (!ticket);
  }
  <button onClick={ticketHandler} className={`${ticket? 'is-success': ''} button`}>1-5</button>
  <button onClick={ticketHandler} className={`${ticket? 'is-success': ''} button`}>6-9</button>

in this example both ticket ‘1-5’ and ticket ‘6-9’ light up green

Can’t pass request body through next-http-proxy-middleware

I’ve been trying to create a frontend using nextjs for a backend I have running in Java.

I’m using the npm package next-http-proxy-middleware and it seems that either my request body is being dropped or I’m using the package incorrectly.

Here’s the entirety of my ./src/api/[…all].ts file

import type { NextApiRequest, NextApiResponse } from 'next'
import httpProxyMiddleware from 'next-http-proxy-middleware'

type Data = {
  name: string
}

export const config = {
  api: {
    externalResolver: true,
  },
}

export default (req: NextApiRequest, res: NextApiResponse) => {
  httpProxyMiddleware(req, res, {
    target: `http://${process.env.REACT_APP_URL}`,
    changeOrigin: true,
  })
}

and here’s the snippet of code where I attempt to login, the form that supplies this data is built using react-hook-form

const onSubmit: SubmitHandler<Inputs> = async (data: any) => {
    //console.log('username', watch('username'), 'password', watch('password'))
    const response = await axios.post(
      '/api/session',
      new URLSearchParams({
        email: data.username,
        password: data.password,
      })
    )
  }

I do see that it’s connecting to my backend since I’m getting an error that’s generated by my Java program and not by next.js, but it just tells me that the email is null which leads me to believe that my args are being lost in translation

"Cannot invoke "String.trim()" because "email" is null - NullPointerException (DataManager:149 < PermissionsManager:508 < SessionResource:111 < ...)"

I am able to get it working using vanilla react so I’m sure it’s something I’m doing wrong in the implementation of the next-http-proxy-middleware but I’ve been bashing my head against the wall a little too long on this. I appreciate all the help, thanks!

How to insert the php array into another array using a loop?

<?php
 include_once("connect.php");
$query = "
select date, sum(amount) as total
from expenses
where date <= NOW()
and date >= Date_add(Now(),interval - 7 day)
group by date;";
    $dateArray = Array();
    $result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo $row["total"];
    echo $row["date"];
      array_push($dateArray,$row);
  }}

echo $dateArray[0]["total"];
$dataPoints = array(
    array("y" => 25, "label" => "Sunday"),
    array("y" => 15, "label" => "Monday"),
    array("y" => 25, "label" => "Tuesday"),
    array("y" => 5, "label" => "Wednesday"),
    array("y" => 10, "label" => "Thursday"),
    array("y" => 0, "label" => "Friday"),
    array("y" => 20, "label" => "Saturday")
);
 
?>

I tried to run it like this and got an error, so not sure if I can set each of the array elements “y” as one of the amounts and “label” as a unique date like this

$dataPoints = array(

foreach($dateArray as $item) {
 array("y" => $dateArray("amount"), "label" => $dateArray("date")0)
}
)

How do you display the date of the latest GitHub commit on a website

I have a website where I want to show the user the date of when it was last updated. (to show the data on the site is updated)
Since I use Netlify to show the main branch on my GitHub repo, I was hoping to show the lastest commit date to the main branch.

I want it to say “Last updated {latest GitHub commit}“

How do I make this work with javascript? I am new to coding, so I would need as much info on how to use the API as possible. Thank you.

I found this, but I don’t know how to extrapolate the data I need from it.
https://api.github.com/repos/:owner/:repo/branches/master

Image slider using HTML, CSS, JS, having

I’ve created an image slider using html and JS.
One problem I’ve come across that I cant quite work myself around is how the image slider transmits multiple images for each slide when the dimensions of the image does not perfectly fit the box. I would like to change this code so that there is only one image displayed at a single time + the image is centered to the box.
does anyone have any suggestions on to how I would edit this?
please let me know if any additional information is needed.

          <div class="carousel-container">
                  <i class="fa fa-arrow-left" id="prevBtn" aria-hidden="true"></i>
                  <i class="fa fa-arrow-right" id="nextBtn" aria-hidden="true"></i>
                  <div class="carousel-slide">
                    <img src="public/images/homme.jpeg" id="lastClone" alt="">
                    <img src="public/images/homme.jpeg" alt="">
                    <img src="public/images/homme.jpeg" alt="">
                    <img src="public/images/homme.jpeg" alt="">
                    <img src="public/images/homme.jpeg" id="firstClone" alt="">
                  </div>
                </div>
              </div>
const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');

const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');

let counter = 1;
const size = carouselImages[0].clientWidth;

carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';

//Button Listeners

nextBtn.addEventListener('click',()=>{
    if(counter >= carouselImages.length -1){
        return;
    }
    carouselSlide.style.tranisition = "transform 0.4s ease-in-out"
    counter++;
    carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});


prevBtn.addEventListener('click',()=>{
    if(counter <= 0){
        return;
    }
    carouselSlide.style.tranisition = "transform 0.4s ease-in-out"
    counter--;
    carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});

carouselSlide.addEventListener('transitonend',()=>{

    if(carouselImages[counter].id === 'lastclone'){
        carouselSlide.style.transition = "none";
        counter = carouselImage.length - 2;
        carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
    }
    if(carouselImages[counter].id === 'firstclone'){
        carouselSlide.style.transition = "none";
        counter = carouselImage.length - counter;
        carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
    }    
});



Swap bar chart group on click using D3.js

this is what i have now
https://jsfiddle.net/xsLrv6a2/9/

basically what i want is this: when i click on a stack of X color, i want for every bar to swap that group with the stack on the botton of the bar for a more clear comparison. all of this must be done with a smooth transition

so for exemple if i click on the green stack of the first bar, i want for every bar, green and red chart to swap position. So, from now on, green is gonna be at the botton so if click another color, its gonna swap with green etc.
other colors of the bars update their position aswell to accomodate the difference

right now i managed to give every group an id and color and attach a onclick function but i have difficulty doing the rest

.attr("fill", d => color(d.key))
        .attr("id",  d => d.key)
      //  .on("click", swap)

thanks for the help!

Angular Display all the Svgs in the view

Hi I am trying to display all the Svgs into html but it displays only one. Here is my

preview:any;

component.ts

 async DisplaySVG() {
        await this.carComponent.Download().then(data =>{
         data.map((sample)=>{
      
    this.preview = this.sanitizer.bypassSecurityTrustHtml(sample)
      })
        }).catch(error =>{
          console.log(error)
        });
       
      } 

and this is my

component.html

<div [innerHTML]="preview">

  </div>

notice data is .Svg and I am using Sanitizer to bypass Security trust and currently they are showing only one svg but I want all of them.

How can I do it here? thanks

How to convert scaling from SVG units to pixels using scale formula?

Previously, I asked how to obtain the real coordinates (d) of a path when a transformation is applied, finally I decided to investigate the transformation formulas, I have already seen the translation, and now I am seeing the scaling (scale), I managed to do a scaling Basically the formula is:

x’ = x * sx

y’ = y * sy

Where:

x is equal to the x coordinate.

y is equal to the y coordinate.

sx or/and sy is equal to the scale factor.

x’ or/and y' is equal to the new size or coordinate.

But I can’t get the scale factor to increase or move the coordinates based on pixels, that is, assuming I have the following svg:

<svg width="300" height="300" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
     <rect x="0" y="0" width="100" height="100" fill="red" />
     <path id="element" d="M5, 5 L50, 5 L50, 45 L5, 45 Z" fill="none" stroke="white" /> 
</svg>

The d attribute (command) of <path id="my-path" d="M5, 5 L50, 5 L50, 45 L5, 45 Z" fill="none" stroke="white" />, If I wanted to scale this path using a scale factor of 2, it would be:

M = 5 * 2, 5 * 2
M = 10, 10

L = 50 * 2, 5 * 2
L = 100, 10

L = 50 * 2, 45 * 2
L = 100, 90

L = 5 * 2, 45 * 2
L = 10, 90

// result

M10, 10 L100, 10 L100, 90 L10, 90

But, going back to the beginning, how do I make it scale based on pixels? Playing around, I managed to guess that if the scale factor is:

1.1 = 15px -> therefore, the total width and height of the path will grow every 15px.

1.01 = 0.5px -> therefore, the total width and height of the path will grow every 0.5px.

But, as I mentioned, I guess it… Is there a formula to do this conversion? I want it to scale to 1px, 2px, 2.5px, etc, etc, for now I only need 1px.

I hope you have understood what I want to do, I hope you can help me.

Note: the svg is being added directly to the HTML.