Javascript fetch giving CORS error despite using GH pages and CORS Proxies

I am working on a virtual piano application, and I’m having a lot of issues with trying to fetch audio files from github. Specifically, I keep getting the errors

Access to fetch at 'https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 

GET https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3 net::ERR_FAILED 200 (OK)
@ piano.js:57 ready  

Uncaught (in promise) TypeError: Failed to fetch at createAudioBuffers (piano.js:57:26) at ready (piano.js:28:26) at piano.js:13:5

In my code, I am simply calling fetch via

const c4AudioURL = "https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3";   
const c4AudioFetch = fetch(c4AudioURL);  

I am using Live Server on VSCode, so I tried to deploy my site to GH Pages to see if that would fix things, but I still got the errors. After trying two different CORS proxies to see if that would help, there was again no change.

Am I missing something here? I suppose It’s that possible that I’m missing something in my code or in the way I’m using Github, as I’m a pretty inexperience programmer. I’ve been stuck on this for a while, so I appreciate any ideas you might have!

Styling Not Applying Next.js 14.4

My next.js 14.04 tailwindcss styling is not applying. I am only using next.js as a frontend framework, without utilizing it backend capabilities.
But the problem is, the styling isn’t working on production.
I have my tailwindcss utilities at the global css file.

I tried it on development mode and it worked, but failed on production.

MutationObserver callback keeps firing

I’m trying to have a MutationObserver watch for changes to a page title and immediately reset the title back to the original text. This partially works, but the first time the page title is changed, my callback keeps firing and the page grinds to a halt. I’ve tried disconnecting the observer in my callback, and that stops it from looping, but I actually need it to keep observing, so it isn’t a solution.

What am I doing wrong?

function resetTitle(title) {
    document.title = title[0].oldValue;
    console.info("Reset the page title.");
}

let observer = new MutationObserver(resetTitle);

observer.observe(document.querySelector('title'), {
  childList: true,
  subtree: true,
  characterDataOldValue: true
});

How to iterating through JSON object [closed]

this is my solution and it seems quite simple and effective:

here is the example:
text

`

<head>
    <script>
        function exploreElement(element, div) {  // get the schema or JSON object
            for (const item in element) {   // for each element in the object
                if (element.hasOwnProperty(item)) {     // if it has own property
                    // append the item to the body
                    const parentDiv = document.createElement("div");
                    parentDiv.setAttribute("title", parseInt(div.title) + 1);
                    // catch the value of the item
                    const value = element[item];
                    // add item and value on the same level and same div
                    parentDiv.innerHTML = "level " + parentDiv.title + " " + item;
                    div.appendChild(parentDiv);
                    if (typeof (value) !== "object" && typeof (value) !== "array") {  // if the value is not an object or an array
                        parentDiv.innerHTML += ":" + value;
                    } else {    // if the value is just an object or an array
                        exploreElement(value, parentDiv);  // iterate the value as element
                    }
                } else {
                    console.log("item without properties");
                }
            }
        }
        let n = 0;
        // get json schema
        fetch("/database/sportExerciseJson.schema.json")
            .then(response => response.json())
            .then(schema => {
                document.body.title = 0;
                exploreElement(schema, document.body);
            })
            .catch(error => console.log(error));

    </script>
    <style>
        div {
            padding: 5px;
            border: solid 1px;
        }

    </style>
</head>

<body>

</body>

`

I have tried to explore all properties and objects or array inside an JSON object.

Is that the best way of doing it or there are some better options?

Item in shopping cart dissapears once I navigate to a different page Django

I am creating a e-commerce website with Django and I stumbled onto a problem I cannot solve.
If i click on add to cart button, the added product shows up in the shopping cart. However, if i navigate to lets say home page ( or any other page ) the newly added product is not displayed no more in the shopping cart.

In JS file I have added some code for debugging.
In views I have done the same, although with the current code I have parsed in here, most of the logging is already removed.

Any suggestions how I can solve this?

I have added logging to server side to debug. I have solved quite a bit there already.

On the client side ( atleast, thats what i suspect where the rootcause may lie), the logging is still there.

views:

def add_to_cart(request):
    try:
        cart_product = {
            "product_name": request.GET["product_name"],
            "product_price": request.GET["product_price"],
            "product_quantity": int(request.GET["product_quantity"]),
        }
        
        product_id = str(request.GET["product_id"])

        if "cart_data_obj" in request.session:
            cart_data = request.session["cart_data_obj"]
            
            if product_id in cart_data:
                # Product already exists in the cart, update the quantity
                cart_data[product_id]['product_quantity'] += int(cart_product['product_quantity'])
            else:
                # Product doesn't exist, add it to the cart
                cart_data[product_id] = cart_product
            
            request.session["cart_data_obj"] = cart_data
        else:
            # Cart is empty, initialize it with the current product
            cart_data = {product_id: cart_product}
            request.session["cart_data_obj"] = cart_data

        # Calculate total quantity for all products in the shopping cart
        total_quantity_cart = sum(product_data['product_quantity'] for product_data in cart_data.values())
        request.session["total_quantity_cart"] = total_quantity_cart

        return JsonResponse({
            "data": request.session["cart_data_obj"],
            "totalcartitems": len(request.session["cart_data_obj"]),
            "total_quantity_cart": request.session["total_quantity_cart"]
        })

    except Exception as e:
        print(e)
        return HttpResponse(status=500)

JS :

$(document).ready(function () {
    // Bind the cartUpdated event listener once when the document is ready
    $(document).on('cartUpdated', function () {
        // Add code here to update other elements on the page
        console.log('Cart Updated. Update other UI elements if needed.');
    });

    $("#add_to_cart_btn").on("click", function () {
        let product_quantity = 1;
        let product_id = $(this).closest('.col-12').find('.product_name').attr('id').split('_')[1];
        let product_name = $(".product_name").text();
        let product_price = $(".product_price").text();
        let this_val = $(this);

        console.log("Product ID : ", product_id);
        console.log("Product Name : ", product_name);
        console.log("Product Price : ", product_price);
        console.log("Product Quantity", product_quantity);
        console.log("Current Element : ", this_val);

        // preparing data from client side to get called in server side
        $.ajax({
            url: "/cart/",
            data: {
                "product_id": product_id,
                "product_name": product_name,
                "product_price": product_price,
                "product_quantity": product_quantity,
            },
            dataType: "json",
            beforeSend: function () {
                console.log("Adding products to cart...");
            },
            success: function (response) {
                console.log("Success Response:", response);

                if (response.total_quantity_cart !== undefined) {
                    $(".cart_items_count").text(response.total_quantity_cart);
                    console.log("Total Quantity Updated:", response.total_quantity_cart);
                } else {
                    console.log("Error: 'total_quantity_cart' not found in response.");
                }

                this_val.html("Item Added To Cart!");
                // Trigger the cartUpdated event
                $(document).trigger('cartUpdated');
            },
            error: function (xhr, status, error) {
                console.log("Error:", error);
            },
            complete: function () {
                console.log("Request complete");
            }
        });
    });
});

html element:

<a class="nav-link active" aria-current="page" href="#">Shopping Cart<span class="badge rounded-pill cart_items_count">{{ total_quantity_cart }}</span></a>

Substituting OR operator (||) for more concise answer matching?

I’m using React JS.
My current code works, but I’m looking to make it more concise.

I’m doing validation for user inputs. I’m saying “if the user input doesnt match A or B or O, then set it as invalid answer and turn it red”.

        switch (_selectedField) {
            case 'Blood Type':
                if (userInput !== 'A' | userInput !== 'B'|userInput !== 'O')
                setIsInValid(true)
                

I have multiple Fields where user inputs answers. That’s what the switch statement is for, to set condition for each _selectedField.
I’m wanting to rewrite my OR (||) operator, as it could become excessive for Fields that have 30 correct answers.

Please let me know a more effective way than using (||) and if possible, please give me some examples.

Thank you so much

Find where two (tangent) lines intersect an enclosing circle

I have two concentric circles and two tangent lines originating from a (single) point on the outer circle. I want to determine where the extension of the tangent lines intersect the outer circle. If it matters, this is in JS, drawing on a canvas.

enter image description here

I know the coordinates and/or values for A, R, r, Tb, Tc, [and the center of the circles, of course, which we can assume is at (0, 0)]. I need to find the coordinates of “B” and “C”.

Any help/suggestions welcome.

Why are my component smaller when accessing it specifically

I have created my own components library and it should be tree shakable. But by using the VSCode extension importCost I can see that by accessing the specific component the size is significal smaller.

enter image description here

The main file that exports the components look like this:

export {ButtonVariants} from "./components/Button/buttonVariants"
export {LoadingDots} from './components/LoadingDots/LoadingDots'
export {Icon} from './components/Icon/Icon'
export type {IconTypes} from './components/Icon/Icon'

And the component itself:

export const LoadingDots = () => {
    return (
        <div className="flex items-center justify-center">
            <div className="mx-[2px] h-2 w-2 scale-0 animate-pulsate rounded-full" />
            <div className="mx-[2px] h-2 w-2 scale-0 animate-pulsate rounded-full [animation-delay:0.2s]" />
            <div className="mx-[2px] h-2 w-2 scale-0 animate-pulsate rounded-full [animation-delay:0.2s]" />
        </div>
    );
};

Output after publish:

enter image description here

Is it just the extension being wrong or have I done something wrong?

Error 404 when i’m up my page using vercel

it’s my first time here.

I’m trying to up my application into vercel, but i’m facing the 404 error.

My project have 3 pages.

the main page: pagina-inicial > index.html
the 2nd: inserindo-informacoes > index.html
3rd one: exibindo-times > index.html

In the first page i have a <a> that redirect to the inserindo-informacoes/index.html. And in the index of inserindo-informacoes also have a <a> that redirect to exibindo-times

I’m using that code in “vercel.json”:

(print)

whats wrong there?

thanks!

I tried to change but in can’t fix.

I expect to solve the problem.

How can i sort items in an array by price by updating order of products in the DOM in JavaScript

So i have my php block at the start of my “shop.php” as thus:

<?php
$jsonPath = './product.json';
$jsonString = file_get_contents($jsonPath);
$data = json_decode($jsonString);
?>

This gets my data from my “products.json” file perfectly.

I also have my dropdown menu as thus:

 <!-- Dropdown menu to trigger sorting start -->
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="triggerId">
    <a class="dropdown-item" href="#" id="sortByName">Name</a>
    <a class="dropdown-item" href="#" id="sortByPrice">Price</a>
    <a class="dropdown-item" href="#" id="sortByReview">Review </a>
    <a class="dropdown-item" href="#" id="sortBySaving">Saving </a>

</div>
<!-- Dropdown menu to trigger sorting end -->

and also my foreach code block as thus:

<!-- for each start -->
<?php foreach ($data as $key => $jsons) {
    foreach ($jsons as $key => $product) {
?>
        <div class="col-lg-4 col-md-6 col-sm-12 pb-1">
            <div class="card product-item border-0 mb-4">
                <div class="card-header product-img position-relative overflow-hidden bg-transparent border p-0">
                    <img class="img-fluid w-100" src="img/<?php echo $product->img; ?>.jpg" alt="">
                </div>
                <div class="card-body border-left border-right text-center p-0 pt-4 pb-3">
                    <h6 class="text-truncate mb-3"><?php echo ucfirst($product->name); ?></h6>
                    <div class="d-flex justify-content-center">
                        <h6>$<?php echo ($product->price); ?></h6>
                        <?php
                        if ($product->was_price == false) {
                        } else {
                            echo "<h6 class='text-muted ml-2'>Was <del>$$product->was_price</del></h6>";
                        }
                        ?>
                        <?php
                        if ($product->reviews == false) {
                        } else {
                            echo "<h6 class='text-muted ml-2'><span>$product->reviews</span>% Review Score </h6>";
                        }
                        ?>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-between bg-light border">
                    <a href="" class="btn btn-sm text-dark p-0"><i class="fas fa-eye text-primary mr-1"></i>View Detail</a>
                    <a href="" class="btn btn-sm text-dark p-0"><i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>
                </div>
            </div>
        </div>

<?php
    }
}



?>
<!-- for each end -->

I want to sort for four categories:

  • Names
  • Price
  • Review and
  • Savings

I have successfully sorted names with my as thus:

<script>
document.addEventListener("DOMContentLoaded", function() {
// Get the dropdown items
var sortByName = document.getElementById('sortByName');
var sortByPrice = document.getElementById('sortByPrice');
var sortByReview = document.getElementById('sortByReview');
var sortBySaving = document.getElementById('sortBySaving');

// Add click event listeners to trigger sorting functions
sortByName.addEventListener("click", function() {
    sortItemsByName();
});

sortByPrice.addEventListener("click", function() {
    sortItemsByPrice();
});

sortByReview.addEventListener("click", function() {
    sortItemsByReview();
});

sortBySaving.addEventListener("click", function() {
    sortItemsBySaving();
});

// Define sorting functions (implement these functions)
function sortItemsByName() {
    // Sort products by name
    var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

    // Get all product items
    var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

    // Sort product items by name
    productItems.sort(function(a, b) {
        var nameA = a.querySelector('.text-truncate').textContent.trim().toUpperCase();
        var nameB = b.querySelector('.text-truncate').textContent.trim().toUpperCase();

        if (nameA < nameB) {
            return -1;
        }
        if (nameA > nameB) {
            return 1;
        }
        return 0;
    });

    // Update the order of product items in the DOM
    productItems.forEach(function(item) {
        productContainer.appendChild(item);
    });
}
</script>

I am trying to sort for Price, Review and Savings but it doesn’t work.

This is what i have tried

<script>
// Define sorting functions
function sortItemsByPrice() {
  // Sort products by price
  var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

  // Get all product items
  var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

  // Sort product items by price (assuming prices are numeric)
  productItems.sort(function(a, b) {
    var priceA = parseFloat(a.querySelector('.text-center h6').textContent.replace('$', ''));
    var priceB = parseFloat(b.querySelector('.text-center h6').textContent.replace('$', ''));

    return priceA - priceB;
  });

  // Update the order of product items in the DOM
  productItems.forEach(function(item) {
    productContainer.appendChild(item);
  });
}

function sortItemsByReview() {
  // Sort products by review score
  var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

  // Get all product items
  var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

  // Sort product items by review score (assuming reviews are numeric)
  productItems.sort(function(a, b) {
    var reviewA = parseInt(a.querySelector('.text-muted span').textContent);
    var reviewB = parseInt(b.querySelector('.text-muted span').textContent);

    return reviewB - reviewA; // Sorting in descending order (highest review first)
  });

  // Update the order of product items in the DOM
  productItems.forEach(function(item) {
    productContainer.appendChild(item);
  });
}

function sortItemsBySavings() {
  // Sort products by savings
  var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

  // Get all product items
  var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

  // Sort product items by savings (assuming savings are numeric)
  productItems.sort(function(a, b) {
    var savingsA = parseFloat(a.querySelector('.text-muted del').textContent.replace('$', ''));
    var savingsB = parseFloat(b.querySelector('.text-muted del').textContent.replace('$', ''));

    return savingsB - savingsA; // Sorting in descending order (highest savings first)
  });

  // Update the order of product items in the DOM
  productItems.forEach(function(item) {
    productContainer.appendChild(item);
  });
}

});
</script>

Please what am i getting wrong and how do i fix this to successfully sort for Price, Reviews and Savings? Thanks

i’m trying one of those on scroll animation but the last image at the bottom on the page doesn’t show up

I did an animation on scroll with jpeg images that cover the whole page and it works quite well for the most part but when i reach the bottom of the page, the last image doesn’t show up.

Chat-gpt was a real help to make it relatively responsive but this problem resulted from the his responsive modified version.

here is the script :

const html = document.documentElement;
const canvas = document.getElementById("canvas1");
const context = canvas.getContext("2d");

const frameCount = 750;
const imageBasePath = 'images/photo_animation4/';

const currentFrame = index => (
    `${imageBasePath}${index.toString().padStart(4, '0')}.jpg`
);

const preloadImages = () => {
    const images = [];
    for (let i = 1; i < frameCount; i++) {
        const img = new Image();
        img.src = currentFrame(i);
        images.push(img);
    }
    return images;
};

let images = preloadImages();
let currentFrameIndex = 6;
let imageLoaded = false;

const updateCanvasSize = () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    if (imageLoaded) {
        updateImage(currentFrameIndex);
    }
};

window.addEventListener('resize', () => {
    updateCanvasSize();
});

const firstImage = new Image();
firstImage.src = currentFrame(1);
firstImage.onload = function () {
    imageLoaded = true;
    updateCanvasSize();
};

const updateImage = index => {
    const img = images[index - 1];
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(img, 0, 0, canvas.width, canvas.height);
};

window.addEventListener('scroll', () => {
    const scrollTop = html.scrollTop;
    const maxScrollTop = html.scrollHeight - window.innerHeight;
    const scrollFraction = scrollTop / maxScrollTop;
    const frameIndex = Math.min(
        frameCount - 1,
        Math.ceil(scrollFraction * frameCount)
    );

    if (frameIndex + 1 !== currentFrameIndex) {
        currentFrameIndex = frameIndex + 1;
        updateImage(currentFrameIndex);
    }
});

setTimeout(() => {
    updateImage(currentFrameIndex);
}, 1000);

This is my first time asking for help on stack overflow so advices on question asking are very welcome.

I can’t get the reducer to change state. That could be happening?

The dispatch data arrives at the reducer, through a Console.log, but the initialstate is maintained.
I want to do it without using redux but it doesn’t work, with Context and useReducer, only

fichier App.js

import { RouterProvider } from "react-router-dom";
import { router } from "./router";
import { AuthProvider } from "./authpage/AuthContext";
import { AuthReducer, initialState } from "./authpage/AuthReducer";

function App() {
  return (
    <AuthProvider initialState={initialState} AuthReducer={AuthReducer}>
      <RouterProvider router={router} />
    </AuthProvider>
  );
}

export default App;

Fichier AuthContext

import { createContext, useReducer } from "react";
export const AuthContext = createContext();

export const AuthProvider = ({ AuthReducer, initialState, children }) => {
  return (
    <AuthContext.Provider value={useReducer(AuthReducer, initialState)}>
      {children}
    </AuthContext.Provider>
  );
};

call from loginSigin

import { register } from "./authActions";

import { AuthContext } from "./AuthContext";
import { types } from "../types";

export const LoginSignIn = () => {
  const registerSubmit = async () => {
    const body = await register(registerName, registerEmail, registerPassword);

    body.user
      ? dispatch({ type: types.AUTH_REGISTER, payload: body.user })
      : dispatch({ types: types.AUTH_ERROR, payload: body.msg });

    console.log(body);
  };

  return (
    <>
      <h1>FORM</h1>

      <form submit={registerSubmit}>
        <buttton submit={registerSubmit}></buttton>
      </form>
    </>
  );
};

The register function works and the console.log shows me this

{ok: false, msg: 'El usuario ya existe'}

and I send it to dispatch
and I send it to the reducer with the dispatch

and finally it goes to reducer:

AuthReducer.js.

I hope that it reaches type , types.AUTH_ERROR and that the state changes but the initialstate always appears

import { types } from "../types";
export const initialState = {
  checking: true,
  uid: null,
  user: null,
  msg: null,
};

export const AuthReducer = (state = initialState, action) => {
  console.log(action.payload);
  console.log(action);

  switch (action.type) {
    case types.AUTH_REGISTER:
      return {
        ...state,
        user: action.payload,
        checking: false,
      };
    case types.AUTH_ERROR:
      console.log("estos es");
      return {
        ...state,
        ...action.payload,
        msg: action.payload,
        checking: false,
      };

    default:
      return state;
  }
};

The response reaches the end, to the reducer, but once there, the state does not change.

WooCommerce, replace woocommerce_before_add_to_cart_button with woocommerce_single_product_summary

I’m modifying this code and need to place the “optionals” div in the product summary hook, if I replace the but if I replace woocommerce_before_add_to_cart_button with woocommerce_single_product_summary `the wk_add_to_cart_validation function fails for each check.

/**
 * Add a custom input field to the product page.
 */
function wk_add_text_field() { ?>
<div class="custom-field-1-wrap">
            <label for="vuoiMontare">Vuoi montare gli attacchi?</label>
            <select id="vuoiMontare" name="vuoiMontare">
                <option value="no"><?php esc_html_e( 'No', 'theme-domain' ); ?></option>
                <option value="si"><?php esc_html_e( 'Sì', 'theme-domain' ); ?></option>
            </select>

            <br>
            <div class="opzioni-attacchi">
                <label for="altezza">
                    <?php esc_html_e( 'Altezza (cm):', 'theme-domain' ); ?>
                </label>
                <input type="text" name='altezza' id='altezza' value=''>
                <br>

                <label for="peso">
                    <?php esc_html_e( 'Peso (kg):', 'theme-domain' ); ?>
                </label>
                <input type="text" name='peso' id='peso' value=''>
                <br>

                <label for="lunghezzaScarpone">
                    <?php esc_html_e( 'Lung. Scarpone (mm):', 'theme-domain' ); ?>
                </label>
                <input type="text" name='lunghezzaScarpone' id='lunghezzaScarpone' value=''>
                <br>

                <label for="eta">
                    <?php esc_html_e( 'Età:', 'webkul' ); ?>
                </label>
                <input type="text" name='eta' id='eta' value=''>
            </div>
        </div>
    <?php
}
add_action( 'woocommerce_before_add_to_cart_button', 'wk_add_text_field' );


/**
 * Validate custom input field value
 */
function wk_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null ) {
    if ( empty( $_POST['vuoiMontare'] ) || $_POST['vuoiMontare'] === 'si' ) {
        // Check if any of the custom fields is empty
        $custom_fields = array( 'altezza', 'peso', 'lunghezzaScarpone', 'eta' );

        foreach ( $custom_fields as $field ) {
            if ( empty( $_POST[ $field ] ) ) {
                $passed = false;
                wc_add_notice( sprintf( __( '%s is a required field.', 'theme-domain' ), ucfirst( $field ) ), 'error' );
            }
        }
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'wk_add_to_cart_validation', 10, 4 );

/**
 * Add custom cart item data
 */
function wk_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    
    // Get form data
    $vuoiMontare = sanitize_text_field($_POST['vuoiMontare']);
    $altezza = sanitize_text_field($_POST['altezza']);
    $peso = sanitize_text_field($_POST['peso']);
    $lunghezzaScarpone = sanitize_text_field($_POST['lunghezzaScarpone']);
    $eta = sanitize_text_field($_POST['eta']);
    
    $cart_item_data['pr_field'] = array(
        'vuoiMontare' => $vuoiMontare,
        'altezza' => $altezza,
        'peso' => $peso,
        'lunghezzaScarpone' => $lunghezzaScarpone,
        'eta' => $eta,
    );
    
    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'wk_add_cart_item_data', 10, 3 );

/**
 * Display custom item data in the cart
 */
function wk_get_item_data( $item_data, $cart_item_data ) {
    if ( isset( $cart_item_data['pr_field'] ) ) {
        $item_data[] = array(
            'key'   => __( 'Montare attacchi?', 'theme-domain' ),
            'value' => wc_clean( $cart_item_data['pr_field']['vuoiMontare'] ),
        );
        $item_data[] = array(
            'key'   => __( 'Altezza', 'theme-domain' ),
            'value' => wc_clean( $cart_item_data['pr_field']['altezza'] ) . 'cm',
        );
        $item_data[] = array(
            'key'   => __( 'Peso', 'theme-domain' ),
            'value' => wc_clean( $cart_item_data['pr_field']['peso'] ) . 'Kg',
        );
        $item_data[] = array(
            'key'   => __( 'Lunghezza scarpone', 'theme-domain' ),
            'value' => wc_clean( $cart_item_data['pr_field']['lunghezzaScarpone'] ) . 'mm',
        );
        $item_data[] = array(
            'key'   => __( 'Età', 'theme-domain' ),
            'value' => wc_clean( $cart_item_data['pr_field']['eta'] ),
        );
    }
    return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'wk_get_item_data', 10, 2 );

Intellij WebStorm getting localhost instead of api (swagger)

I’m trying to use fetch / post, to send form data to a swagger api hosted by my university. Unfortunately, when I click send the data is sent to localhost instead of the provided https path.

I have changed the port to 8080, allowed unsigned requests and the accepting of external connections.

The code is still being sent to http://localhost:8080/ which produces a 404 error.

What do I need to do to send the data to the correct destination?

Below you can see my code used to try to send the data.

  fetch('https://correct-path.com/api/v1/data', {
        method: 'POST',
        headers: {
            Authorization: 'TOKEN',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });

Text position off in Jest test running in Jenkins

I’m using Jest and Puppeteer to write some DOM-related tests. The tests are passing successfully on both my local machine and a co-worker’s. But I get a few failing tests when running them in Jenkins. The failing ones are all similar in terms of how they’re set up, so I’ve pasted a simplified version of one of them below. I basically have a group element (called container) with a text element rendered inside. I expect the x-positions of container and its parent SVG to be the same, but instead container is further to the left by 1 unit. This is due to the text inside of container being off by 1. When this test runs in Jenkins, the console.log messages in the test prints:

container x: 7 svg x: 8 text x: 7

But I was expecting the output to be:

container x: 8 svg x: 8 text x: 8

which is also what I get on my local machine.

I’m wondering if anyone has an idea of what might be going on. Why would running the tests in Jenkins cause the text node to be positioned further to the left than its parent container?

The html setup for my test…

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Test Page</title>

  <!-- set root font size -->
  <style>
    html {
      font-size: 16px;
    }
    body {
      font-size: 0.875rem;
    }
  </style>
  
  <script type="module">
    const svgSideLength = 800
    window.testUtil = { svgSideLength }
  </script>
</head>
<body>
</body>
</html>

My test…

  test('dummy test', async () => {
    const result = await page.evaluate(async function () {
      // svgSideLength equals 800
      const { svgSideLength } = testUtil
      document.body.innerHTML = `
      <svg height=${svgSideLength} width=${svgSideLength}>
        <g transform='translate(0, 5)'>
          <text>The quick brown fox jumps over the lazy dog</text>
        </g>
      </svg>`
      
      const containerBoundingRect = document.querySelector('g').getBoundingClientRect()
      const svgBoundingRect = document.querySelector('svg').getBoundingClientRect()
      const textBoundingRect = document.querySelector('text').getBoundingClientRect()

      console.log('container x: ', containerBoundingRect.x,
        'svg x: ', svgBoundingRect.x, 'text x: ', textBoundingRect.x)

      return containerBoundingRect.x === svgBoundingRect.x
    })

    expect(result).toBe(true)
  })

Some dependency versions FYI:
Puppeteer 16.2.0
Jest 29.7.0