How to send an attachment with a form in html using Web3Forms

/Im using Web3Forms and the email sends,but the problem is that the attachment shows up as plain text and doesnt open./

 <form action="https://api.web3forms.com/submit" method="post">
            <input type="hidden" name="access_key" value="261987ac-8575-439e-8b44-14d9896905b8">
            <div class="form-group">
                <label for="firstName">Name <span>(required)</span></label>
                <div class="name-inputs">
                    <input type="text" id="firstName" name="firstName" placeholder="First Name" required>
                    <input type="text" id="lastName" name="lastName" placeholder="Last Name" required>
                </div>
            </div>
            <div class="form-group">
                <label for="email">Email <span>(required)</span></label>
                <input type="email" id="email" name="email" placeholder="Email" required>
            </div>
            <div class="form-group">
                <label for="subject">Something about yourself<span>(required)</span></label>
                <input type="text" id="Description" name="Description" placeholder="Description" required>
            </div>
            <div class="form-group">
                <label for="file">Upload your CV <span>(required)</span></label>
                <input type="file" id="myFile" name="filename">
            </div>
            <button type="submit">Send</button>
        </form>

React JS how to properly set Cookies using custom reactHooks?

I am creating the login functionalities of my website but having trouble with setting the Cookie with the token from my backend. The token is being returned properly and is setting the user in the UserContext, however the part where the token is to be stored in the browser Cookie (such as when viewed in the browser developer options Application tab) it is not showing or being set. I have no idea whether the issue is in the Login.jsx or in the useStorage.js. Here are the current codes:

./src/hooks/useStorage.js

import { useCallback, useEffect, useState } from 'react';
import Cookies from 'js-cookie';

function useLocalStorage(key, defaultValue) {
    return useStorage(key, defaultValue, window.localStorage);
};

function useSessionStorage(key, defaultValue) {
    return useStorage(key, defaultValue, window.sessionStorage);
};

function useCookiesStorage(key, defaultValue, options) {
    return useStorage(key, defaultValue, null, options);
};

function useStorage(key, defaultValue, storageObject, options) {
    const [value, setValue] = useState(() => {
        if (storageObject) {
            const jsonValue = storageObject.getItem(key);
            if (jsonValue != null) return JSON.parse(jsonValue);
        } else {
            const cookieValue = Cookies.get(key);
            if (cookieValue != null) return JSON.parse(cookieValue);
        }

        if (typeof defaultValue === "function") {
            return defaultValue();
        } else {
            return defaultValue;
        }
    });

    useEffect(() => {
        if (value === undefined) {
            if (storageObject) {
                return storageObject.removeItem(key);
            } else {
                return Cookies.remove(key, options);
            }
        }

        const jsonValue = JSON.stringify(value);
        if (storageObject) {
            storageObject.setItem(key, jsonValue);
        } else {
            Cookies.set(key, jsonValue, options);
        }
    }, [key, value, storageObject, options]);

    const remove = useCallback(() => {
        setValue(undefined);
    }, []);

    return [value, setValue, remove];
};

export {
    useLocalStorage,
    useSessionStorage,
    useCookiesStorage
};

./src/pages/Login.jsx

import '../assets/css/login.css';
import { Button, Col, Container, Form, Image, InputGroup, Row, Stack } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useContext, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { GetUser, SignIn } from '../utils/Auth';
import Swal from 'sweetalert2';
import { useCookiesStorage } from '../hooks/useStorage';
import UserContext from '../UserContext';

function Login() {
    const { setUser } = useContext(UserContext);
    const navigate = useNavigate();
    const [uidValue, setUidValue] = useState('');
    const [upassValue, setUpassValue] = useState('');
    const [,setToken] = useCookiesStorage('__Secure-auth.session-token', null, {httpOnly: true, secure: true, sameSite: 'Strict'});

    async function LoginUser(e) {
        e.preventDefault();

        Swal.fire({
            title: 'Logging in',
            didOpen: () => {
                Swal.showLoading();
            },
            text: 'Please wait',
            showConfirmButton: false,
            allowOutsideClick: false
        });
        const response = await SignIn(uidValue, upassValue); // Returns response message and token
        
        if (!response || !response.token) {
            Swal.close();
            Swal.fire({
                title: `${response.message}!`,
                icon: 'error',
                text: 'Try again',
                timer: 2000,
                timerProgressBar: false,
                showConfirmButton: false,
                allowOutsideClick: false
            });
        }
        else {
            setToken(response.token); // Set the Cookie '__Secure-auth.session-token'
            const user = await GetUser(response.token); // returns user details
            
            if (!user || !user._id) {
                Swal.close();
                Swal.fire({
                    title: `${response.message}!`,
                    icon: 'error',
                    text: 'Try again',
                    timer: 2000,
                    timerProgressBar: false,
                    showConfirmButton: false,
                    allowOutsideClick: false
                });
            }
            else {
                Swal.close();
                Swal.fire({
                    title: 'Login successful!',
                    icon: 'success',
                    text: 'Redirecting to dashboard, please wait...',
                    timer: 2000,
                    timerProgressBar: false,
                    showConfirmButton: false,
                    allowOutsideClick: false
                })
                .then((result) => {
                    if (result.dismiss === Swal.DismissReason.timer) {
                        setUidValue('');
                        setUpassValue('');
                        setUser({ // Sets user context with details from fetch request
                            uid: user._id,
                            user: user.username,
                            role: user.role
                        });
                        navigate('/dashboard');
                    }
                });
            }
        }
    };

    return (...rest of code);
};

export default Login;

I hope someone could help me with what I am doing wrong, I am fairly new to React JS and studying through project based learning.

DOMContentLoaded event is not firing code outside it working

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript  </title>

    <meta charset="UTF-8" />
  </head>

  <body>
    <div class="App"></div>

    <script src="./index.mjs" type="module"></script>
  </body>
</html>

index.mjs

console.log("Script loaded");   this is priting only

document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM fully loaded and parsed");  //nothig prints inside this event
});

I want code inside DOMContentLoaded to work but its not working at all in simple code. Can someone tell me what I am doing wrong here.

Intellisense not working for object destructuring in Visual Studio Code

The intellisense of VSCode doesn’t work when destructuring an object, it returns any as the type, no matter what.

I tried:

/**
 * @returns {{name:String,surname:String}}
 */
function Test(){
 return {name:"John",surname:"Doe"};
}
const {name,surname} = Test(); // Intellisense shows "any" for both 

I was expecting to get proper type information, in this case, string.

Retrieve data from CKEditor using ajax to not cause the page to reload*

Here is my code first:

forms code from product.html:

...
{% comment %} Review Form Start`` {% endcomment %}
<div class="container">
  <section class="review-section col-12 mt-4">

    {% comment %} Display All Reviews {% endcomment %}
    <h3 class="hide-review-heading">Reviews</h3>
    {% for review in reviews %}
      <div class="review">
        <p><strong>{{ review.user.username }}</strong> - {{ review.rating }} stars</p>
        <p>{{ review.review | safe }}</p>
      </div>
      <hr>
    {% empty %}
      <p>No reviews yet. Be the first to write a review!</p>
    {% endfor %}

    <h3 class="hide-review-heading">Write a Review</h3>
    <strong class="" id="review-response"></strong>
    <form action="{% url 'home:ajax_add_review' p.pid %}" method="POST" class="hide-review-form" id="commentForm">
      {% csrf_token %}
      <div class="form-group mt-3">
        {{ review_form.review }}
      </div>
      <div class="form-group mt-3">
        {{ review_form.rating.label_tag }}<br>
        {{ review_form.rating }}
      </div>
      <br>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
  </section>
</div>
{% comment %} Review Form End {% endcomment %}

{% endblock body %}

review.js:

console.log("review.js loaded");

$("#commentForm").submit(function(e) {
  e.preventDefault();

  $.ajax({
    data: $(this).serialize(),
    method: $(this).attr("method"),
    url: $(this).attr("action"),
    dataType: "json",
    success: function(response) {
      console.log("Comment saved to DB")

      if (response.bool) {
        $("#review-response").html("Review saved successfully");
        // Assign a class and remove text-danger class if there
        $("#review-response").addClass("text-success");
        $("#review-response").removeClass("text-danger");
        $(".hide-review-form").hide();
        $(".hide-review-heading").hide();
      }
      else {
        $("#review-response").html("Error saving review");
        $("#review-response").addClass("text-danger");
        $("#review-response").removeClass("text-success");
      }

    }
  });
});

urls.py:

from django.urls import path
from . import views

app_name = "home"

urlpatterns = [
    path('', views.index, name='index'),
    path('collections/<slug:collection_handle>', views.collections, name="collections"),
    path('product/<slug:product_handle>', views.product, name="product"),
    path('minimal_product/<slug:product_handle>', views.minimal_product, name="minimal_product"),
    # path('products/', views.products, name="products"),
    path('search/', views.search, name="search"),
    path('products/', views.product_list, name="product-list"),
    path('product-quick-view/<int:product_id>/', views.product_quick_view, name='product_quick_view'),
    path("ajax-add-review/<pid>", views.ajax_add_review, name="ajax_add_review"),
]

Product and ajax_add_review function from views:

def product(request, product_handle):    
    product = Product.objects.filter(handle=product_handle, product_status="in_review").first()
    review_form = ProductReviewForm()
    reviews = ProductReview.objects.filter(product=product)

    if not product:
        raise Http404
    context = {
        "p": product,
        "review_form": review_form,
        "reviews": reviews,
        }

    return render(request, 'home/product.html', context=context)

def ajax_add_review(request, pid):
    product = Product.objects.get(pid=pid)
    user = request.user

    # for key, value in request.POST.items():
    #     print(f'{key}: {value}')

    review_text = request.POST.get('review')
    rating = request.POST.get('rating')

    print(f"Review is: {review_text}")

    if not review_text or not rating:
        print("Review text or rating is missing")
        return JsonResponse({'bool': False, 'error': 'Review text or rating is missing'})

    review = ProductReview.objects.create(
        user=user,
        product=product,
        review=review_text,
        rating=rating,
    )
    
    
    context = {
        'user': user.username,
        'review': review.review,
        'rating': review.rating,
    }
    
    average_reviews = ProductReview.objects.filter(product=product).aggregate(Avg('rating'))
    
    return JsonResponse(
        {
        'bool': True,
        'context': context,
        'average_reviews': average_reviews,
        }
    )

ProductReviewForm from forms.py:

class ProductReviewForm(forms.ModelForm):
    # review = forms.CharField(widget=CKEditor5Widget(config_name='review', attrs={'placeholder': 'Write your review here...'}), required=False)

    class Meta:
        model = ProductReview
        fields = ['review', 'rating']
        widgets = {
            "review": CKEditor5Widget(
                attrs={"class": "django_ckeditor_5", 'placeholder': 'Write your review here...'}, config_name="review"
            )
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["review"].required = False

Now, when I click submit, the value of rating is retrieved but the value of review, I checked in inspect and instead of {{ review_form.review }}, there was a with the name=”review” and display as none and for ckeditor where you the review is shown. And I believe that the review is retreieved from the .

It was happening from one of the two options which isn’t exactly what I want:

  1. If I click the Submit button, it shows “Error saving review” because of the line in ajax_add_review which says if not review_text or not rating and during that, the text in the review field is automatically added to the , so if I click Submit again, it works.
  2. If I remove e.preventDefault();, and then add the review and click Submit, it redirects me to the page where the JSON successfully generated from ajax_add_review is shown and the data is added successfully to the database with the review.

What I want is: for the page to not reload, the review and rating to be added to the database correctly without having to click the Submit button twice.

Help would be really really apprecaited

How to fix malformed JSON strings in JavaScript? (Asked in technical interview) [closed]

My code:

function fixJson(incompleteJson) {
  let varOcg = incompleteJson.trim();
  try {
    JSON.parse(varOcg);
    return varOcg;
  } catch (e) {
    const quoteRegex = /(w+)(:)/g;
    varOcg = varOcg.replace(quoteRegex, '"$1"$2');
    if (varOcg.endsWith(",")) {
      varOcg = varOcg.slice(0, -1);
    }
    if (!varOcg.endsWith("}") && !varOcg.endsWith("]")) {
      varOcg += "}";
    }
    try {
      JSON.parse(varOcg);
      return varOcg;
    } catch (e) {
      return "Invalid JSON: unable to correct the JSON string.";
    }
  }
}

Sample input 1

input={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math"
}

output={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math"
  }
}

Sample input 2

input={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math
   }
}

output={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math"
  }
}

I need a function, fixJson, that can handle various issues with malformed JSON, such as:

  • Missing closing braces or brackets
  • Unquoted keys or values
  • Incomplete strings

The function should return the corrected JSON string if possible or an error message if the JSON cannot be fixed.

Here’s what I’m looking for:

  1. A function that attempts to repair common issues with malformed JSON.
  2. It should ensure that the output is valid JSON and formatted correctly.
  3. If the JSON cannot be fixed, it should provide an informative error message.

Could you please help me with the implementation of such a function in JavaScript?

Thanks in advance!

Can running this javascript be harmful to my computer? [closed]

Hey a complete novice in code here. One day I noticed a strange looking file that was in my downloads folder and being the idiot I am I decided to double click it without a single thought. When I did, I got a “windows script host” dialog box saying some sort of error. Now upon closer inspection I realized it was a backup of a script that I downloaded for tampermonkey some while back. I know the script works properly on my google chrome, but I’m just afraid that by double clicking on the script in file explorer I may have screwed up something on my computer…. So can anyone knowledgeable give me some insight in the simplest terms into what might have happened when I double clicked on the file? Could I have damaged my PC?

I tried opening it in notepad to see what was up, but being a complete novice in coding, I just can’t tell what happened.

Here is the code I copied from notepad

// ==UserScript==
// @name            YouTube Playlist AutoPlay
// @namespace       https://github.com/crazyrabbit0
// @version         2.1.4
// @description     AutoPlay next Playlist item in YouTube
// @author          CrazyRabbit
// @match           http://*.youtube.com/*
// @match           https://*.youtube.com/*
// @icon            https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant           none
// @license         GPL-3.0-or-later; http://www.gnu.org/licenses/gpl-3.0.txt
// @copyright       2023+, CrazyRabbit (https://github.com/crazyrabbit0)
// @homepageURL     https://github.com/crazyrabbit0/UserScripts
// @supportURL      https://github.com/crazyrabbit0/UserScripts/issues/new?assignees=crazyrabbit0&labels=help+wanted&template=&title=YouTube%20Playlist%20AutoPlay%20-%20Issue
// @run-at          document-start
// @noframes
// @downloadURL https://update.greasyfork.org/scripts/480708/YouTube%20Playlist%20AutoPlay.user.js
// @updateURL https://update.greasyfork.org/scripts/480708/YouTube%20Playlist%20AutoPlay.meta.js
// ==/UserScript==

(function() {
    'use strict'

    let elements = {
        player: null,
        next_video: null,
        progress: null,
        loop: null
    }

    let loaded = {
        player: false,
        progress: false
    }

    let loop = {
        code: null,
        value: null,
        map: {
            //'M21': '',
            'M20': 'playlist',
            'M13': 'video'
        }
    }

    function play_next_video(player = elements.player) {
        elements.next_video = document.querySelector('ytd-playlist-panel-video-renderer[selected] + ytd-playlist-panel-video-renderer > a')
        if(player.classList.contains('ended-mode')) {
            let has_video_loop = elements.loop.querySelector('path')?.getAttribute('d').substring(0, 3) === 'M13'
            //let ads = document.querySelector('.video-ads')
            if(!has_video_loop) {
                elements.next_video?.click()
            }
            //console.log('video-ended')
        }
        else if(player.querySelector('.html5-ypc-title')?.innerText) {
            elements.next_video?.click()
            //console.log('video-cannot-start')
        }
    }

    function reset_loop(progress = elements.progress) {
        if(!progress.hasAttribute('hidden')) {
            loop.code = elements.loop.querySelector('path')?.getAttribute('d').substring(0, 3)
            loop.value = loop.code.replace(/Md+/, function(match) { return loop.map[match] || '' })
            //console.log('progress-started')
        }
        else {
            switch (loop.value) {
                case 'video':
                    elements.loop.click()
                    /* falls through */
                case 'playlist':
                    setTimeout(function() { elements.loop.click() }, 1)
            }
            //console.log('progress-finished')
        }
    }

    let loaded_check = setInterval(function() {
        if(!loaded.player && elements.player && elements.next_video) {
            loaded.player = true
            play_next_video()
            new MutationObserver(function(mutations) {
                for(const mutation of mutations) {
                    play_next_video(mutation.target)
                }
            }).observe(elements.player, {
                attributeFilter: [ "class" ]
            })
        }
        else {
            elements.player = document.querySelector('div#movie_player')
            elements.next_video = document.querySelector('ytd-playlist-panel-video-renderer[selected] + ytd-playlist-panel-video-renderer > a')
        }

        if(!loaded.progress && elements.progress && elements.loop) {
            loaded.progress = true
            reset_loop()
            new MutationObserver(function(mutations) {
                for(const mutation of mutations) {
                    reset_loop(mutation.target)
                }
            }).observe(elements.progress, {
                attributeFilter: [ "hidden" ]
            })
        }
        else {
            elements.progress = document.querySelector('yt-page-navigation-progress')
            elements.loop = document.querySelector('ytd-playlist-loop-button-renderer button')
        }

        if(Object.values(loaded).every(Boolean)) {
            clearInterval(loaded_check)
            //console.log('all-elements-loaded')
        }
    }, 500)
})()

How can I create a function to fix malformed JSON strings in JavaScript?

I’m working on a project where I need to handle JSON strings that are sometimes malformed. Specifically, I need a JavaScript function that can automatically repair these JSON strings and return them in a valid format.

For example, consider the following malformed JSON string:

const json = '{"key1":{"key2":"value1","key3":"value2"},"anotherkey":"va';

This string is missing a closing quote and a closing brace. The expected output should be:

{"key1":{"key2":"value1","key3":"value2"},"anotherkey":"va"}

I need a function, fixJson, that can handle various issues with malformed JSON, such as:

  • Missing closing braces or brackets
  • Unquoted keys or values
  • Incomplete strings

The function should return the corrected JSON string if possible or an error message if the JSON cannot be fixed.

Here’s what I’m looking for:

  1. A function that attempts to repair common issues with malformed JSON.
  2. It should ensure that the output is valid JSON and formatted correctly.
  3. If the JSON cannot be fixed, it should provide an informative error message.

Could you please help me with the implementation of such a function in JavaScript?

Thanks in advance!

NestJS: DTO transform default values not working if parameter is not passed in the payload

I’ve created a controller that receives a POST/ ... request.
one of the parameters is optional and it’s for example called contentType.
in the service i check if the contentType is equal to something and regarding to the result it does something.
because the parameter is not mandatory, I want to set it a default value.
in that case I used @Transform() decorator in the DTO.
When I do the call I don’t see the default values I defined in the decorator it in the service.

Expected:

sort = {date: -1}

contentType = ‘json’

Result in Service:

sort = undefined

contentType = undefined

My NestJS Config:
Using nestJS V10
reflect-metadata version: ^0.2.2″

  1. Main.ts:

    const app = await NestFactory.create(AppModule);
    ...
    app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      transformOptions: { enableImplicitConversion: true },
      whitelist: true,
      }),
    );

  1. DTO:

    export class ListDto {
    ... more...
        
    @IsObject()
    @IsOptional()
    @Transform(({ value }) => value ?? { date: -1 })
    sort?: Record<string, SortOrder>;  // Types Defined above I just don't want to pollute the example.
            
    @IsString()
    @IsOptional()
    @IsIn(['json', 'xlsx', 'csv'], {
    message: 'contentType must be one of: json, xlsx, csv',
    })
    @Transform(({ value }) => value ?? 'json')
    contentType?: Extension;
    } 

  1. Controller:

 @Post('list')
 async list(@Body() list: ListDto): Promise<any> {
   try {
     console.log(list.sort) // <-- Expected default value defined in decorator, but undefined
     console.log(list.contentType) // <-- Expected default value defined in decorator, but undefined
     return await this.someService.list(list);
   } catch (error) {
    ....
   }
 }

  1. request body:

    {
      "param1" : "Some value",
      "param2" : "Some other"
      //NOT Passing sort or contentType
    }

  1. Service method declaration:

async list({
...more...
sort,
contentType,
}: ListeDto): Promise<List> {
console.log(contentType) <-- Expect to see the default value from the decorator, but undefined
console.log(sort)  <-- Expect to see the default value from the decorator, but undefined
...some implementation...
}

Where did I do wrong?
Or what am I missing?

[Vue warn]: Hydration node mismatch with v-if

I get the error “[Vue warn]: Hydration node mismatch” when using the “v-if” condition in my NavigationHeader.vue component.

Here’s the technical stack used :

  • Vue.js v3
  • Nuxt.js v3
  • Nuxt UI

Hydration completed but contains mismatches.

[Vue warn]: Hydration node mismatch

I do understand that hydration is the process by which a Vue application takes server-side generated HTML content and transforms it into an interactive client-side application.

Below is the code snippet from the NavigationHeader.vue component causing the error. I’ve included two potential solutions that seem to solve the issue, although I’m not sure they’re appropriate in this situation. ⬇️

<script setup lang="ts">
const { isAuthenticated, logout } = useAuthentication();

const handleLogout = async () => {
  try {
    await logout();
  } catch (e) {
    console.error(e);
  }
};
</script>
<!-- Hydration node mismatch error. -->
<template>
  <BaseButton v-if="!isAuthenticated" label="Login" to="/login" />
  <BaseButton v-if="isAuthenticated" label="Logout" @click="handleLogout" />
</template>

<!-- Works because buttons are rendered client-side only. However, this option doesn't suit me because I want my button components to be rendered at the same time as the NavigationHeader.vue component. -->
<template>
  <ClientOnly>
    <BaseButton v-if="!isAuthenticated" label="Login" to="/login" />
    <BaseButton v-if="isAuthenticated" label="Logout" @click="handleLogout" />
  </ClientOnly>
</template>

<!-- Works because the component is rendered in the DOM but hidden with CSS. -->
<template>
  <div v-show="!isAuthenticated">
      <BaseButton label="Login" to="/login" />
  </div>
  <div v-show="isAuthenticated">
      <BaseButton label="Logout" @click="handleLogout" />
  </div>
</template>

I wonder what the best practice is for dealing with “[Vue warn]: Hydration node mismatch” errors ?

Start camera in mobile browser by appending body, causes flickering with touch event, with Unity WebGL

I am working on a WebGL AR app using Unity and ARWT library. This library works by using aframe and AR.js to start the device camera, read the camera feed from the HTML/JavaScript end, and send it to Unity.

Originally, the library demo starts the device camera (with permission granted) when the webpage is opened. I’d like to modify this so that the camera turns on only when the user presses a button. So I append the camera feed using iframe to html body when press button in Unity.

However, the screen flickers when touched on mobile browsers (Safari, Chrome, etc.). The flickering does not occur when the camera starts while the webpage is opening. It only happens when the camera feed is appended to the HTML afterwards. (Here is a flickering demo on my GitHub)

I found that the flickering is caused by the touchstart and touchend events. These events are registered on unitycanvas, which renders and controls the Unity content. The touch events are registered from framework.js, which is generated by Unity.

I’ve tried set the -webkit-tap-highlight-color to transparent to prevent the touch event effects, but it didn’t work. One way that does eliminate the flickering is to disable touch events entirely but this also removes all user interaction effects in Unity, which is not ideal for my needs.

how to write in node js local dynamodb runs locally not in actual lambda

this simple aws.js I’m using to run dynamoDB locally

"use strict";
 const AWS = require("aws-sdk");


 AWS.config.dynamodb = {
     region: "eu-west-2",
     endpoint: "http://localhost:8000"
 };


 module.exports = ()=>{
     return new AWS.DynamoDB.DocumentClient();
 };

How to make sure this runs locally only. I want to make sure this won’t run in actual lambda after I merge my PR. So in actual lambda it should use the real dynamoDB

React page is not showing when there is an error, is there any method that we can use to see the actual error?

React page is not showing when there is an error, is there any method that we can use to see the actual error.

trying to built a simple game on the base of react. that work like lottery ticket

import { getTicket, sum } from "./helper";
import "./Lottery.css";
import { useState, useEffect, useRef } from "react";
import party from "party-js";

export default function Lottery() {
    let [ticket, setTicket] = useState(getTicket(3));
    let isWining = sum(ticket);
    const winnerRef = useRef(null);

    useEffect(() => {
        if (isWining === 15) {
            party.confetti(winnerRef.current, {
                count: party.variation.range(60, 90),
            });
        }
    }, [isWining]);
    
    let newTicket = () => {
        setTicket(getTicket(3));
    }

    return (
        <div>
            <div>
                <h1>This is a lottery game</h1>
            </div>
            <div className="Ticket">
                <span>{ticket[0]}</span>
                <span>{ticket[1]}</span>
                <span>{ticket[2]}</span>
            </div>
            {isWining === 15 ?
                <p ref={winnerRef}>Winner</p> :
                <p>Loser</p>}
            <div>
                <button onClick={newTicket}>Buy New Ticket</button>
            </div>
        </div>
    )
}

this is my code but not worked

How to implement proper cart logic?

The cart behaves incorrectly: When adding a product for the first time, only its quantity is displayed, the image and ID are not transmitted, I tried to find out the value of the ID that is transmitted when adding the first product via console.log and it returned null, but if I add another product to the cart it is displayed correctly. PRODUCT.HTML:

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', () => {
      // Получение данных о продукте
      const urlParams = new URLSearchParams(window.location.search);
      const productId = urlParams.get('id');

      if (productId) {
        fetch(`/product/${productId}`)
          .then(response => response.json())
          .then(product => {
            const buttonsContainer = document.getElementById('buttonsContainer');

            document.getElementById('product-name').textContent = product.name;
            document.getElementById('price').textContent = `Цена: ${product.price}`;
            document.getElementById('short-sub').textContent = product.short_description;
            document.getElementById('productDescription').textContent = product.description;
            document.getElementById('article').textContent = `Артикул: ${product.article}`;
            document.getElementById('volume').textContent = `Объем: ${product.volume}`;
            document.getElementById('points').textContent = `Баллы: ${product.points}`;
            document.getElementById('productImage1').src = `images/${product.image_2_url}`;
            // Дополнительно можете добавить код для изображения и других данных

            buttonsContainer.innerHTML = `
                <a href="order.html"><button class="buy-button"><b>КУПИТЬ</b></button></a>
                <button class="cart-button" data-product-id="${product.id}" data-image-url="${product.image_url}"><b>В КОРЗИНУ</b></button>
              `;
            
            // Добавление товаров в корзину
            const addToCartButtons = document.querySelectorAll('.cart-button');

            addToCartButtons.forEach(button => {
              button.addEventListener('click', (event) => {
                const imageUrl = event.target.getAttribute('data-image-url');
                addToCart(productId, imageUrl);
              });
            });
          })
          .catch(error => {
            console.error('Error fetching product data:', error);
          });
      }
    

    function addToCart(productId, imageUrl) {
  let cart = JSON.parse(localStorage.getItem('cart')) || [];
  let productExists = false;

  cart.forEach(item => {
    if (item.id === productId) {
      item.quantity += 1;
      productExists = true;
    }
  });

  if (!productExists) {
    cart.push({ id: productId, quantity: 1, image: imageUrl });
  }

  localStorage.setItem('cart', JSON.stringify(cart));

  alert('Товар добавлен в корзину');
}

    });
</script>

CART.HTML:

<script type="text/javascript">
            document.addEventListener('DOMContentLoaded', () => {
  displayCart();
});

function displayCart() {
  const cart = JSON.parse(localStorage.getItem('cart')) || [];
  console.log('Loaded cart:', cart); // Добавлено логирование

  const cartContainer = document.getElementById('cart-container');

  cart.forEach(item => {
    const productElement = document.createElement('div');
    productElement.className = 'product';
    productElement.innerHTML = `<div class="q"><b><p>${item.quantity}</p></b></div><img src="${item.image || 'images/default.png'}">`; // Указано изображение по умолчанию
    cartContainer.appendChild(productElement);
  });
}

        </script>

Here is the logic that should be instead: I add product 1 to the cart, which was empty, then in the cart I see this product with quantity 1, when I add this product again, the quantity increases, then I add product 2 to the cart where there is already product 1 , I go to the cart and see product 1 and product 2 with different quantity values ​​and so on.

Medusa.JS – req.body empty in POST middleware

Pulling my hair out over this. Thanks in advance to anyone who can take a look. Any idea why req.body would be empty? Medusa.JS should be using bodyParser by default, yes? It was working earlier today and now it isn’t. Clearly something has changed and I can’t figure out what. This is my middlewares.ts file:

async function myTestFunc(req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) {
  const logger = req.scope.resolve<Logger>('logger');
  console.log("Request BODY!", JSON.stringify(req.body))
  console.log("Request PARAMS!", JSON.stringify(req.params))
  console.log("Customer ID!", JSON.stringify(req.user?.customer_id))
  next();
}

export const config: MiddlewaresConfig = {
  routes: [
    {
      matcher: '/store/carts/:id/line-items',
      middlewares: [authenticateCustomer(), myTestFunc]
    }
  ],
};

Thanks again, much appreciated.