How can I fix my Flask server’s 405 error that includes OpenAi api?

Im trying to make add an api into my webpage and have never used any Flask server before, I have never used Javascript too so this is a completely brand new learning expirience. My problem is that I keep recieiveing a 405 error code saying that the method is not allowed. I keep on using the POST method but it isnt working, I am banking that my issue maybe with my html code more than my flask server because the code is extremly generic and simple.

import openai
from flask import Flask, request, jsonify

app = Flask(__name__)

openai.api_key = '**my key is in here**'

@app.route('/', methods=['POST'])
def chat():
    data = request.get_json()
    message = data.get('message')
    
    response = openai.Completion.create(
        model="gpt-3.5-turbo",  
        prompt=message,
        max_tokens=50
    )

    return {'response': response.choices[0].text.strip()}

if __name__ == '__main__':
    app.run(port=5000)
async function sendMessage() {
            const message = document.getElementById('message').value;
            document.getElementById('chat-box').innerHTML += `<div>You: ${message}</div>`;
            
            const response = await fetch('/', {
                method: "POST",
                body: JSON.stringify({ message }),
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            const data = await response.json();
            document.getElementById('chat-box').innerHTML += `<div>Bot: ${data.reply}</div>`;
            document.getElementById('message').value = '';
        }

I tried changing up the structure of the code, I uninstalled flask and reinstalled it again. I’ve also extensively used chatgpt to try and come up with better code but it just kept taking me in circles. Im hoping someone can help with this.I even tried a simple server that just said hello world which worked, but I truly think the issue might be with my javascript. Also I am a beginner and this is supposed to be one of my first coding projects so please take it easy on me if possible. Thanks.

Chrome Extension on youtube.com – How can I use the Youtube Ajax navigation in Javascript?

I’m developping a Chrome Extension that adds new feeds content on Youtube.com

I would like to add new thumbnails links that will open new video but I can’t figure out how can I use their ajax navigation.

As everything is loaded in ajax its not easy to understand how it really works.

Here are the following tests I made

Test 1 : adding a simple a link with /watch?v=2SNThp1YiU4 as href attribute value will load the page without ajax …

Test 2 : in Devtools when I inspect a thumbnail link and change the href attribute, if I click the link the default page will be loaded, not the one I edited which means the video ID was certainly hardcoded in the event listener declaration ?!

So, how can I add custom link to Youtube.com DOM so it uses the proper Youtube ajax navigation ?

Thanks in advance

How to get dynamic url based content displayed on a web page hosted on cloudflare pages

I need to display dynamic content on a webpage based on the url, for example –
exampledomain.com/username

on page load: the username will be sent to the backend server and content will be fetched from the server. Then it will be displayed in html divs i created for that content.
I just need the url to load the webpage and then javascript to access the username and make an api call using it, kind of like how express.js does it on my backend server (examplebackend.com/username123)

app.post("/:username", (req, res) => {
    res.json({ data: data })
});

if exampledomain.com/username is not possible then i am fine by using
exampledomain.com/user?username=name but how do i do this (is it possible without php using just javascript?)


The website is hosted on cloudflare pages.
The backend server is hosted on render running on node.js

PS. I am new to stack overflow and full stack web development in general

.feature file is not being recognized when trying to execute .feature file with webdriverIO

enter image description here

enter image description here

Trying to execute
npx wdio –spec .step_definitionsLoginfeature.feature

I am able to see the app open but as soon as it does, the app crashes

[0-0] 2024-07-21T15:51:01.750Z INFO @wdio/local-runner: Run worker command: run
[0-0] 2024-07-21T15:51:01.982Z WARN @wdio/mocha-framework: Unable to load spec files quite likely because they rely on browser object that is not fully initialized.
[0-0] browser object has only capabilities and some flags like isMobile.
[0-0] Helper files that use other browser commands have to be moved to before hook.
[0-0] Spec file(s): file:///C:/Users/anup1/mobile-app-automation/step_definitions/Loginfeature.feature
[0-0] Error: Error: ERR_UNKNOWN_FILE_EXTENSION .feature C:Usersanup1mobile-app-automationstep_definitionsLoginfeature.feature

UI Not Updating When Checkbox is Clicked Inside an iframe (Google Chrome Extension)

I am working on a Chrome extension that interacts with an iframe on a webpage. What I want to do is click on a checkbox inside the iframe, after which the UI should update as if a regular user clicked on the checkbox. However, even though the checkbox is clicked (as confirmed by the logs), the UI does not update.

This is part of my code:

var checkbox = iframedoc.getElementsByClassName("leaflet-control-layers-selector")[0];
if (checkbox) {
    console.log("Checkbox found");
    console.log(checkbox.checked);
    if(!checkbox.checked) {
        checkbox.click();
        console.log("Checkbox clicked");
        console.log(checkbox.checked);
    }
} else {
    console.log("Checkbox not found");
}

is there some limitation that I’m missing or don’t know about?

Disabling variations and add custom suffix to out of stock variations on woocommerce

I want to add a feature for the variables that out of stock to disable them and add a “out of stock” suffix so that when users select the variables, they will know which variable has an existing variable and they can select only that one and the others will be disabled and that out of stock suffix as well. be shown next to the variable name.
The code I edited is as follows, but it only disables the variables and does not show the “out of stock” suffix.

// PHP function to disable out-of-stock variations and inline jQuery script
add_filter('woocommerce_variation_is_active', 'bbloomer_grey_out_variations_out_of_stock', 10, 2);
function bbloomer_grey_out_variations_out_of_stock($is_active, $variation) {
    if (!$variation->is_in_stock()) return false;
    return $is_active;
}

// Inline jQuery script
add_action('wp_footer', 'custom_inline_jquery_script');
function custom_inline_jquery_script() {
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $(window).load(function() {
                $('body.single-product .product.type-product table.variations td.value select option').each(function(index) {
                    var optionText = $(this).text();
                    if (optionText.indexOf(" - sold out") >= 0) {
                        $(this).addClass('sold-out');
                    }
                });
            });
        });
    </script>
    <?php
}

How to efficiently Locate Source Code from Logs in SvelteKit Apps?

We have a SvelteKit App, and when bugs appear, I noticed that we spend a good amount of time locating the files and line numbers from where the logs are. (Especially for the server logs)

So I thought that this should be a common problem with an easy solution: a logging library that logs the file and the line number for every line of log out of the box and works for the Browser and Nodejs.

But this seems to be not the case. Either the logging libraries don’t support it (like e.g. Pino or Winston), or you need to add some custom string parsing by throwing an error and extracting from it the file and line number, which has reasonable performance implications.

So I’m asking myself

  1. Is it 2024 still not possible to have this out of the box somehow without the performance implications?
  2. Or is the question about file and line number the wrong question, and there are other good options to locate the piece of code connected to a log message?

How to Integrate old jquery code into new

Good day. I have js and php code for botton “Save position” on the site which I can not integrate into ajax. Plese help.

Code for botton “Save position” on the site:

<td class="right"><a id="sds_rev_save_mod" href="javascript:void(0)" class="button"><?php echo ControllerModulerevslideropencart::

$lang_var['sds_Save_Position']?></a><span style="display:none;" class="loader_round" id="sds_rev_save_mod_loader">updating... </span><span id="sds_rev_save_mod_success" class="success_message"></span></td>

This code working on site with jQuery 1.7.1:

//start save module position value
var initposvalSliderButton = function(ajaxAction){
    jQuery("#sds_rev_save_mod").click(function(){

    var data = UniteSettingsRev.getsdsformvalue("sds_rev_mod_form");
        

        // data = $('form#sds_rev_mod_form').serializeArray();

        
        if(ajaxAction == "add_slider_pos_val"){
            UniteAdminRev.setAjaxLoaderID("sds_rev_save_mod_loader");
            UniteAdminRev.setAjaxHideButtonID("sds_rev_save_mod");
            UniteAdminRev.setSuccessMessageID("sds_rev_save_mod_success");
        }
        UniteAdminRev.ajaxRequest(ajaxAction ,data);
    });
}

Need integrate into this code after – button_save_slider, button_save_slider_t . Site working on jQuery 2.1.1:

var rs_install_slider = {},
    rs_install_ids = [],
    rs_install_url = !1,
    RevSliderAdmin = new (function () {
        function e() {
            var e = jQuery("#spinner_color").val(),
                i = jQuery("#use_spinner");
            (0 != i.val() && 5 != i.val()) || (e = "#ffffff");
            var t = jQuery("#spinner_preview .tp-loader.tp-demo");
            t.hasClass("spinner0") || t.hasClass("spinner1") || t.hasClass("spinner2") ? t.css({ backgroundColor: e }) : t.find("div").css({ backgroundColor: e });
        }
        function i(i, t) {
            var r = jQuery("#use_spinner");
            i.find(".tp-loader").remove(),
                i.append('<div class="tp-loader tp-demo"><div class="dot1"></div><div class="dot2"></div><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>'),
                i.find(".tp-demo").addClass("spinner" + r.val()),
                "-1" == r.val() || 0 == r.val() || 5 == r.val() ? jQuery("#spinner_color_row").css({ display: "none" }) : jQuery("#spinner_color_row").css({ display: "block" }),
                e();
        }
        var t = this,
            r = null,
            a = function (e) {
            
            jQuery("#button_save_slider,#button_save_slider_t").click(function () {
                    var i = { params: RevSliderSettings.getSettingsObject("form_slider_params"), main: RevSliderSettings.getSettingsObject("form_slider_main"), template: jQuery("#revslider_template").val() };
                    "update_slider" == e &&
                        ((i.sliderid = jQuery("#sliderid").val()),
                        (i.params.custom_css = rev_cm_custom_css.getValue()),
                        (i.params.custom_javascript = rev_cm_custom_js.getValue()),
                        UniteAdminRev.setAjaxLoaderID("loader_update, #loader_update_t"),
                        UniteAdminRev.setAjaxHideButtonID("button_save_slider,button_save_slider_t"),
                        UniteAdminRev.setSuccessMessageID("update_slider_success,#update_slider_success_t")),
                        UniteAdminRev.ajaxRequest(e, i);
                });
            };

        t.initLayerPreview = function () {
            jQuery("#button_preview_slider-tb").click(function () {
                var e = jQuery("#sliderid").val();
                y(e);
            });
        };
        var s = function () {
                var e = jQuery("#alias").val(),
                    i = '[rev_slider alias="' + e + '"]';
                "" == e && (i = rev_lang.wrong_alias), jQuery("#shortcode").val(i);
            },
            l = !1;
        t.load_slider_template_html = function () {
            return (
                l
                    ? (jQuery("#template_area").addClass("show"), jQuery("#template_area").trigger("showitnow"))
                    : UniteAdminRev.ajaxRequest("load_template_store_sliders", {}, function (e) {
                          e.success && (jQuery(".revolution-template-groups").html(e.html), jQuery("#template_area").addClass("show"), jQuery("#template_area").trigger("showitnow"), initTemplateSliders(), (l = !0));
                      }),
                !0
            );
        };
        var n = !1;
        t.load_slide_template_html = function () {
            return (
                n
                    ? (jQuery("#template_area").addClass("show"), jQuery(".revolution-template-groups").perfectScrollbar(), scrollTA())
                    : UniteAdminRev.ajaxRequest("load_template_store_slides", {}, function (e) {
                          e.success &&
                              (jQuery(".revolution-basic-templates").html(e.html), (n = !0), templateSelectorHandling(), jQuery("#template_area").addClass("show"), jQuery(".revolution-template-groups").perfectScrollbar(), scrollTA());
                      }),
                !0
            );
        };
  

This code working on site with jQuery 1.7.1:

//end save module position value


// start
            jQuery("#sds_rev_save_mod").click(function(){
                initposvalSliderButton("add_slider_pos_val");
            });
// end

Need integrate after this code. Site working on jQuery 2.1.1:

 jQuery(".button_duplicate_slider").click(function () {
                        var e = this.id.replace("button_duplicate_", "");
                        jQuery("#dialog_duplicate_slider").dialog({
                            modal: !0,
                            resizable: !1,
                            width: 250,
                            height: 200,
                            closeOnEscape: !0,
                            dialogClass: "tpdialogs",
                            create: function (e) {
                                jQuery(e.target).parent().find(".ui-dialog-titlebar").addClass("tp-slider-new-dialog-title");
                            },
                            buttons: {
                                Close: function () {
                                    jQuery(this).dialog("close");
                                },
                                Duplicate: function () {
                                    return "" != jQuery("#rs-duplicate-animation").val() && void UniteAdminRev.ajaxRequest("duplicate_slider", { sliderid: e, title: jQuery("#rs-duplicate-animation").val() }, function (e) {});
                                },
                            },
                        });
                    }),

This code working on site with jQuery 1.7.1:

case 'add_slider_pos_val':
$newdata = array();
if(!empty($data)){
    $k = array_keys($data);
    $k = preg_replace_callback('/[[0-9]+/', create_function('$match','return "";'), $k[0]);
    foreach($data as $key => $arr){
        $newdata[$k][] = $arr;
    }
    $data = $newdata;
}
sdsconfig::editSetting('revslideropencart',$data);
self::ajaxResponseSuccess(__("Slider Position Save SuccessFully",REVSLIDER_TEXTDOMAIN));
break;

Need integrate into this code. Site working on jQuery 2.1.1:

//          
            if(!RevSliderFunctionsWP::isAdminUser() && apply_filters('revslider_restrict_role', true)){
                switch($action){
                    case 'change_specific_navigation':
                    case 'change_navigations':
                    case 'update_static_css':
                    case 'add_new_preset':
                    case 'update_preset':
                    case 'import_slider':
                    case 'import_slider_slidersview':
                    case 'import_slider_template_slidersview':
                    case 'import_slide_template_slidersview':
                    case 'import_slider_online_template_slidersview_new':
                    case 'fix_database_issues':
                        RevSliderFunctions::throwError(__('Function Only Available for Adminstrators', 'revslider'));
                        exit;
                    break;
                    default:
                        $return = apply_filters('revslider_admin_onAjaxAction_user_restriction', true, $action, $data, $slider, $slide, $operations);
                        if($return !== true){
                            RevSliderFunctions::throwError(__('Function Only Available for Adminstrators', 'revslider'));
                            exit;
                        }
                    break;
                }
            }
            
            //verify the nonce
            $isVerified = rev_token_valid($nonce);
                       // $isVerified = true;
            if($isVerified == false){
                RevSliderFunctions::throwError("Wrong request");
                exit;
            }
                                        
            switch($action){
                            case 'install_plugin':
                                $addon_admin = new Rev_addon_Admin('rev_addon', RevSliderGlobals::SLIDER_REVISION);
                                $addon_admin->install_plugin();
                                break;
                             case 'deactivate_plugin':
                                $addon_admin = new Rev_addon_Admin('rev_addon', RevSliderGlobals::SLIDER_REVISION);
                                $addon_admin->deactivate_plugin();
                                break;
                            case 'activate_plugin':
                                $addon_admin = new Rev_addon_Admin('rev_addon', RevSliderGlobals::SLIDER_REVISION);
                                $addon_admin->activate_plugin();
                                break;
                case 'add_new_preset':
                    
                    if(!isset($data['settings']) || !isset($data['values'])) self::ajaxResponseError(__('Missing values to add preset', 'revslider'), false);
                    
                    $result = $operations->add_preset_setting($data);
                    
                    if($result === true){
                        
                        $presets = $operations->get_preset_settings();
                        
                        self::ajaxResponseSuccess(__('Preset created', 'revslider'), array('data' => $presets));
                    }else{
                        self::ajaxResponseError($result, false);
                    }
                    
                    exit;
                break;

Error in fetch operation while restoring data from db

I’m trying to get a button to show me the details stored in the database when clicking it.I keep get this message in the console:

There was a problem with the fetch operation:

SyntaxError

SyntaxError: Unexpected token ‘<‘, “<?php

ini_”… is not valid JSON

This is the JS code:

document.getElementById('showDetailsButton').addEventListener('click', function() { 
  fetch('get_details.php')
    .then(response => {
      if (!response.ok) {
      throw new Error('Network response was not ok');
      }
      return response.json();
})
   .then(data => {
  document.getElementById('usernameDisplay').innerText = 'Username: ' + data.username;
    document.getElementById('passwordDisplay').innerText = 'Password: ' + data.password;
      document.getElementById('sequenceDisplay').innerText = 'RGB Sequence: ' + data.sequence;    
     document.getElementById('details').style.display = 'block';   
})
     .catch(error => { 
       console.error('There was a problem with the fetch operation:', error); 
    });
});

And the php code (get_details.php):

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

include 'db.php';
$username = $_SESSION['username'] ?? null;
  if ($username === null) {
    header('HTTP/1.1 400 Bad Request')
    echo json_encode(['error' => 'Username is not set in session.']);
exit();
}
   $stmt = $conn->prepare("SELECT username, password, sequence FROM user_data WHERE username = ?");

$stmt->execute([$username]);
$data = $stmt >fetch(PDO::FETCH_ASSOC);
if ($data === false) {

  header('HTTP/1.1 404 Not Found');
  echo json_encode(['error' => 'User data not found.']);
  exit();
  }

  $response = ['username' => $data['username'],'password' => $data['password'],'sequence' => $data['sequence']
];
  header('Content-Type: application/json');
  echo json_encode($response);
?>

How to get the invite_link object with Telegram API? I want to check through which invite link a new member joins the group chat

I want to check through which invite link a new member joins the group chat. According to the Telegram API docs, there should be an invite_link type when listening on the Chat_member update.

ChatMemberUpdated
This object represents changes in the status of a chat member.

Field   Type    Description
chat    Chat    Chat the user belongs to
from    User    Performer of the action, which resulted in the change
date    Integer Date the change was done in Unix time
old_chat_member ChatMember  Previous information about the chat member
new_chat_member ChatMember  New information about the chat member
invite_link ChatInviteLink  Optional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only.
via_join_request    Boolean Optional. True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator
via_chat_folder_invite_link Boolean Optional. True, if the user joined the chat via a chat folder invite link

But I failed to get the invite_link object with the following code:

const TelegramBot = require('node-telegram-bot-api');
require ('dotenv').config();

const token = process.env.BOT_TOKEN;
const bot = new TelegramBot(token, { polling: true });

bot.on('chat_member', (msg) => {
  const newMemberInviteLink = msg.invite_link ? msg.invite_link : "Unknown Invite Link";
  console.log(newMemberInviteLink);
})

When I try to console log the entire msg, I get the entire ChatMemberUpdated type, but there is no invite_link even though I am sure the new member joined the group chat with a generated invite link other than the primary invite link:

Received update: {
  chat: {
    id: -1002225700353,
    title: 'TestReferralChatgroup',
    username: 'TestReferralChatgroup',
    type: 'supergroup'
  },
  from: {
    id: 5189356713,
    is_bot: false,
    first_name: 'rii',
    last_name: 'un',
    username: 'LilKimbom'
  },
  date: 1721558379,
  old_chat_member: {
    user: {
      id: 5189356713,
      is_bot: false,
      first_name: 'rii',
      last_name: 'un',
      username: 'LilKimbom'
    },
    status: 'left'
  },
  new_chat_member: {
    user: {
      id: 5189356713,
      is_bot: false,
      first_name: 'rii',
      last_name: 'un',
      username: 'LilKimbom'
    },
    status: 'member'
  }
}

When I try to console log the entire msg, I get the entire ChatMemberUpdated type, but there is no invite_link even though I am sure the new member joined the group chat with a generated invite link other than the primary invite link:

Received update: {
  chat: {
    id: -1002225700353,
    title: 'TestReferralChatgroup',
    username: 'TestReferralChatgroup',
    type: 'supergroup'
  },
  from: {
    id: 5189356713,
    is_bot: false,
    first_name: 'rii',
    last_name: 'un',
    username: 'LilKimbom'
  },
  date: 1721558379,
  old_chat_member: {
    user: {
      id: 5189356713,
      is_bot: false,
      first_name: 'rii',
      last_name: 'un',
      username: 'LilKimbom'
    },
    status: 'left'
  },
  new_chat_member: {
    user: {
      id: 5189356713,
      is_bot: false,
      first_name: 'rii',
      last_name: 'un',
      username: 'LilKimbom'
    },
    status: 'member'
  }
}

OverwriteModelError: Cannot overwrite AddOnsDatabase model once compiled. [Typescript]

Im using nextjs

i keep getting the error

OverwriteModelError: Cannot overwrite AddOnsDatabase model once compiled.

to fix this error i am using the OR operator to check if the model already exists

import mongoose from "mongoose";

const AddOnsDatabaseSchema = new mongoose.Schema({
  name: String,
  limit: String,
  required: Boolean,
});

const AddOnsDatabase =
  mongoose.model("AddOnsDatabase") ||
  mongoose.model("AddOnsDatabase", AddOnsDatabaseSchema);
export default AddOnsDatabase;

this fixes the errors but messes up typescript as when i was using

const AddOnsDatabase = mongoose.model("AddOnsDatabase", AddOnsDatabaseSchema);

and used this model like this:

"use server";
import { connectDB } from "@/lib/mongodb";
import AddOnsDatabase from "@/models/AddOnsDatabase";
import { DBAddon } from "@/types/temp";
export async function GetAddOns(): Promise<DBAddon[]> {
  await connectDB();
  const addons = await AddOnsDatabase.find().lean();
  console.log(addons);
  if (!addons) return [];
  const addonsToReturn = addons.map((addon) => {
    return {
      id: addon._id ? addon._id.toString() : "",
      name: addon.name ? addon.name : "",
      limit: addon.limit ? addon.limit : "",
      required: addon.required ? addon.required : false,
    };
  });
  return addonsToReturn;
}

addons would have this type

const addons: (FlattenMaps<{
    name?: string | null | undefined;
    limit?: string | null | undefined;
    required?: boolean | null | undefined;
}> & {
    _id: Types.ObjectId;
})[]

but after using the OR operator const AddOnsDatabase = mongoose.model("AddOnsDatabase") || mongoose.model("AddOnsDatabase", AddOnsDatabaseSchema);

addons has type

const addons: (FlattenMaps<any> & Required<{
    _id: unknown;
}>)[]

please help me find a way to not get that error and also infer types automatically using Model.findById()

I have tried the above stated things

ThreeJs codepen to React component

I’ve been trying to move this codepen.io to a react component, this what I did:

React Custom Hook

import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { createNoise4D } from 'simplex-noise';
import { random } from 'chroma-js';

interface Config {
  el: string;
  fov: number;
  cameraZ: number;
  xyCoef: number;
  zCoef: number;
  lightIntensity: number;
  ambientColor: number;
  light1Color: string;
  light2Color: string;
  light3Color: string;
  light4Color: string;
}

interface UseBackgroundAnimationReturn {
  noiseInputRef: React.RefObject<HTMLInputElement>;
  heightInputRef: React.RefObject<HTMLInputElement>;
}

const useBackgroundAnimation = (config: Config): UseBackgroundAnimationReturn => {
  const defaultConfig: Config = {
    fov: 75,
    cameraZ: 75,
    xyCoef: 70,
    zCoef: 20,
    lightIntensity: 1,
    ambientColor: 0xff0000,
    light1Color: '#0E09DC',
    light2Color: '#1CD1E1',
    light3Color: '#18C02C',
    light4Color: '#ee3bcf',
    ...config,
  };

  const conf = { ...defaultConfig, ...config };
  const rendererRef = useRef<THREE.WebGLRenderer>();
  const cameraRef = useRef<THREE.PerspectiveCamera>();
  const sceneRef = useRef<THREE.Scene>();
  const planeRef = useRef<THREE.Mesh>();
  const lightRefs = useRef<THREE.PointLight[]>([]);
  const mouseRef = useRef(new THREE.Vector2());

  const noiseInputRef = useRef<HTMLInputElement>(null);
  const heightInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const init = () => {
      const canvas = document.getElementById(conf.el) as HTMLCanvasElement;
      if (!canvas) return;

      const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
      const camera = new THREE.PerspectiveCamera(conf.fov);
      camera.position.z = conf.cameraZ;

      rendererRef.current = renderer;
      cameraRef.current = camera;

      updateSize();
      window.addEventListener('resize', updateSize);

      initScene();
      initGui();
      animate();
    };

    const initGui = () => {
      if (noiseInputRef.current) {
        noiseInputRef.current.value = (101 - conf.xyCoef).toString();
        noiseInputRef.current.addEventListener('change', (e: Event) => {
          conf.xyCoef = 101 - (e.target as HTMLInputElement).valueAsNumber;
        });
      }

      if (heightInputRef.current) {
        heightInputRef.current.value = ((conf.zCoef * 100) / 25).toString();
        heightInputRef.current.addEventListener('change', (e: Event) => {
          conf.zCoef = ((e.target as HTMLInputElement).valueAsNumber * 25) / 100;
        });
      }

      document.getElementById('trigger')?.addEventListener('click', updateLightsColors);
    };

    const initScene = () => {
      const scene = new THREE.Scene();
      sceneRef.current = scene;
      initLights();

      const mat = new THREE.MeshLambertMaterial({ color: 0xff0000, side: THREE.DoubleSide });
      // const mat = new THREE.MeshStandardMaterial({ color: 0xffff00, side: THREE.DoubleSide });


      const geo = new THREE.PlaneGeometry(window.innerWidth, window.innerHeight, window.innerWidth / 2, window.innerHeight / 2);
      const plane = new THREE.Mesh(geo, mat);
      planeRef.current = plane;

      scene.add(plane);
      plane.rotation.x = -Math.PI / 2 - 0.2;
      plane.position.y = -25;
      cameraRef.current!.position.z = 60;
    };

    const initLights = () => {
      const lightDistance = 500;

      // Adding Ambient Light
      const ambientLight = new THREE.AmbientLight(0x404040, 1); // soft white light
      sceneRef.current!.add(ambientLight);

      const light1 = new THREE.PointLight(conf.light1Color, conf.lightIntensity, lightDistance);
      const light2 = new THREE.PointLight(conf.light2Color, conf.lightIntensity, lightDistance);
      const light3 = new THREE.PointLight(conf.light3Color, conf.lightIntensity, lightDistance);
      const light4 = new THREE.PointLight(conf.light4Color, conf.lightIntensity, lightDistance);

      light1.position.set(0, 50, 30);
      light2.position.set(0, -50, -30);
      light3.position.set(50, 50, 0);
      light4.position.set(-50, 50, 0);

      lightRefs.current = [light1, light2, light3, light4];

      sceneRef.current!.add(light1);
      sceneRef.current!.add(light2);
      sceneRef.current!.add(light3);
      sceneRef.current!.add(light4);
    };


    const animate = () => {
      setTimeout(() => {

      }, 500);
      requestAnimationFrame(animate);

      animatePlane();
      animateLights();

      rendererRef.current!.render(sceneRef.current!, cameraRef.current!);
    };

    const animatePlane = () => {
      const gArray = planeRef.current!.geometry.attributes.position.array;
      const time = Date.now() * 0.0001;
      const noise4D = createNoise4D();

      for (let i = 0; i < gArray.length; i += 3) {
        gArray[i + 2] = noise4D(gArray[i] / conf.xyCoef, gArray[i + 1] / conf.xyCoef, time, mouseRef.current.x + mouseRef.current.y) * conf.zCoef;
      }

      planeRef.current!.geometry.attributes.position.needsUpdate = true;
    };

    const animateLights = () => {
      const time = Date.now() * 0.001;
      const d = 50;
      lightRefs.current.forEach((light, i) => {
        light.position.x = Math.sin(time * 0.1 * (i + 1)) * d;
        light.position.z = Math.cos(time * 0.2 * (i + 1)) * d;
      });
    };

    const updateLightsColors = () => {
      conf.light1Color = random().hex();
      conf.light2Color = random().hex();
      conf.light3Color = random().hex();
      conf.light4Color = random().hex();

      lightRefs.current[0].color = new THREE.Color(conf.light1Color);
      lightRefs.current[1].color = new THREE.Color(conf.light2Color);
      lightRefs.current[2].color = new THREE.Color(conf.light3Color);
      lightRefs.current[3].color = new THREE.Color(conf.light4Color);
    };

    const updateSize = () => {
      const width = window.innerWidth;
      const height = window.innerHeight;

      rendererRef.current!.setSize(width, height);
      cameraRef.current!.aspect = width / height;
      cameraRef.current!.updateProjectionMatrix();
    };

    init();

    return () => {
      window.removeEventListener('resize', updateSize);
    };
  }, [conf]);

  return {
    noiseInputRef,
    heightInputRef,
  };
};

export default useBackgroundAnimation;

and this is the component where I use it

import useBackgroundAnimation from './useBackgroundAnimation';

const BackgroundComponent: React.FC = () => {
  const { noiseInputRef,
    heightInputRef,
  } = useBackgroundAnimation({
    el: 'backgroundCanvas',
  });

  return (
    <div className="text-center min-h-screen flex flex-col justify-center items-center bg-white">
      <div id="page" className="max-w-3xl mx-auto">
        <header className="mb-6">
          <div className="inner">
            <h3 className="masthead-brand">Background #1</h3>
            <nav className="nav nav-masthead justify-content-center">
              <a className="nav-link" href="https://codepen.io/soju22/" target="_blank" rel="noopener noreferrer">Codepen Profile</a>
              <a className="nav-link" href="https://codepen.io/collection/AGZywR" target="_blank" rel="noopener noreferrer">ThreeJS Collection</a>
            </nav>
          </div>
        </header>

        <main role="main" className="inner cover">
          <h2>Interactive Background</h2>
          <p className="lead">
            This simple interactive background is made with
            <a href="https://threejs.org" target="_blank" rel="noopener noreferrer"> ThreeJS</a>
            and a
            <a href="https://threejs.org/docs/#api/en/geometries/PlaneBufferGeometry" target="_blank" rel="noopener noreferrer"> PlaneBufferGeometry</a>
            animated with Simplex noise.
          </p>

          <form className="w-4/5 mx-auto">
            <div className="form-row">
              <div className="form-group col-sm-6">
                <label htmlFor="noiseInput" className="form-label">Noise Coef</label>
                <input ref={noiseInputRef} type="range" min="1" max="100" className="custom-range" id="noiseInput" />
              </div>
              <div className="form-group col-sm-6">
                <label htmlFor="heightInput" className="form-label">Height Coef</label>
                <input ref={heightInputRef} type="range" min="1" max="100" className="custom-range" id="heightInput" />
              </div>
            </div>
            <div className="form-group col-md-12">
              <button type="button" id="trigger" className="btn btn-sm btn-secondary">Random Colors</button>
            </div>
          </form>
        </main>

        <footer className="mastfoot mt-auto"></footer>
      </div>
      <canvas id="backgroundCanvas"></canvas>
    </div>
  );
};

export default BackgroundComponent;

And this is what I got:

enter image description here

The problem: I can’t replicate the color and the smooth movement.

How to insert script code in php code in script code again [duplicate]

hello Can some one solve my bizzare code, I wrote code then I put a php code inside function variable, and in that function I adding again code inside php,
it means Script code in php code in script code..

var inputan = document.getElementById("inputan");
inputan.addEventListener('keydown', function() {
    if (event.key === 'Enter') {
        alert(inputan.value);
        insertDB(inputan.value)
        inputan.value = "";
    }
});
function insertDB(inputan){
        <?php
        $Nama = ?> <script>inputan.value</script>;
        <?php
        if ( isset($Nama)) {   
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "radian";

            $Type = "test lagi";

            // Create connection
            $conn = mysqli_connect($servername, $username, $password, $dbname);

            // Check connection
            if (!$conn) {
                die("Connection failed: " . mysqli_connect_error());
            }

            // Insert data into the table
            $sql = "INSERT INTO `wew`(`Nama Product`, `Type`) VALUES ('$Nama','$Type')";

            if (mysqli_query($conn, $sql)) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . mysqli_error($conn);
            }

            // Close connection
            mysqli_close($conn);

            // Output data in JSON format
            echo json_encode(array('message' => 'Data inserted successfully'));
            }
        ?>
        
}

I get 401 unauthorized error after successful login in reactjs app with laravel & sanctum

I have created an app with React while using Laravel 10 as back-end (using Sanctum for auth).

When I try to log in on first attempt I get “401: unauthorized” error, but on second attempt it successfully logs in, now if after successful login I logout and again try to login with the same user it works fine.

But if I try a different user the same happens so each user has to try two login attempts in order to be able to successfully log in.

here is my setup on laravel side

auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
], 

my api routes


Route::post('login', LoginController::class)->name('login');
Route::post('logout', function (Request $request) {
    Auth::guard('web')->logout();
});


Route::middleware('auth:sanctum')->group(function () {
    // admin routes here
});

Kernal.php

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array<int, class-string|string>
     */
    protected $middleware = [
        // AppHttpMiddlewareTrustHosts::class,
        AppHttpMiddlewareTrustProxies::class,
        IlluminateHttpMiddlewareHandleCors::class,
        AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        //
        AppHttpMiddlewareHandleQueryStringParams::class,
        AppHttpMiddlewareSwitchLocale::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            IlluminateRoutingMiddlewareThrottleRequests::class . ':api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

    /**
     * The application's middleware aliases.
     *
     * Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
     *
     * @var array<string, class-string|string>
     */
    protected $middlewareAliases = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'precognitive' => IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,
        'signed' => AppHttpMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
    ];
}

LoginController.php

class LoginController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(LoginRequest $request)
    {
        $credentials = $request->validated();

        if (Auth::attempt($credentials)) {
            $user = Auth::user();

            // check if user is active
            if ($user->active != true) {
                return alert_error(__('auth.not_activated'), 422);
            }

            // updated signed_in_at field
            $user = User::find($user->id);
            $user->logged_in_at = Carbon::now();
            $user->save();

            $auth = [
                'uuid' => $user->uuid,
                'role' => $user->role_id,
                'name' => $user->name,
            ];

            return result_success(__('auth.auth_success'), $auth);
        } else {
            return alert_error(__('auth.auth_failed'), 422);
        }
    }
}

here is my reactjs setup

axios configuration

// configure axios
export const http = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  withCredentials: true,
  withXSRFToken: true,
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
});

CsrfCookie component

const HttpCsrfCookie = ({ children }) => {
  useEffect(() => {
    http
      .get(import.meta.env.VITE_CSRF_COOKIE_URL)
      .then((response) => {
        iLog(response);
        iLog("csrf: done");
      })
      .catch((error) => {
        iLog(error.response);
      });
  }, []);

  return children;
};

export default HttpCsrfCookie;

main.js

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <HttpCsrfCookie>
      <HttpInterceptor>
        <QueryClientProvider client={queryClient}>
          <App />
          <ReactQueryDevtools initialIsOpen={false} />
        </QueryClientProvider>
      </HttpInterceptor>
    </HttpCsrfCookie>
  </React.StrictMode>
);

my user login api function

const userLogin = async (post) => {
  try {
    const response = await http.post("login", post);
    const data = response.data;

    return data;
  } catch (error) {
    return error.response;
  }
};

login form submit mutaiton (i use react query)

  const { mutate, isPending } = useMutation({
    mutationFn: userLogin,
    onSuccess: ({ data, success }) => {
      if (success) {
        setAuth(true, data);
        navigate("/");
      } else {
        removeAuth();
      }
    },
  });

  const onSubmit = (formData) => {
    mutate(formData);
  };

note: the setAuth() function set loggedIn to true and saves some basic user info in local storage.

Any help will be greatly appreciated cause this has been bugging for a week now.

With Regards