How to redirect Remote resource to local?

It is a react application created by Umijs.

When I request https://cdn.jsdelivr.net/npm/[email protected]/img/apple/sheets-256/64.png I wish it can be redirect to localhost:8080/64.png.Because the remote resource sometime is slowly.

And then,It was requested by Third-party library.So I’cant use request Interceptor

How to redirect Remote resource to local?

enter image description here

It was requested by Third-party library.So I’cant use request Interceptor

How to remove socket.io default parameters

I want to connect the web socket API of an external server using Vue2.
So, I installed the socket.io library.
However, when I run it, parameter values ​​that I do not want are entered.

Request URL: wss://loki.test.shop/loki/api/v1/tail?query={app=%22test-api%22}/?EIO=4&transport=websocket
parameter values ​​that I do not want are entered : /?EIO=4&transport=websocket

After checking the official documentation, it appears to be the default parameter value.
So I searched and found that I need to change the source code on the server and client sides.
But the websocket API is an external API that I cannot touch.
What action should the front office take to remove the default parameter values?

help me please.

Below is the code I wrote.

ioclientConnect(){
      const wssUrl = 'wss://loki.test.shop'
      const socket = io(wssUrl, {
        path: '/loki/api/v1/tail?query={app=%22test-api%22}',
        transports: ["websocket"],
        extraHeaders: {
          'X-Scope-OrgID': 'test'
        },
        cors: {
          origin: "*",
        },
        timestampRequests: false
      })

      socket.on('message', (message)=>{
        console.log('receive', message)
      })
    }

Text displays multiple times but when I try this, it doesnt display at all

The text kept displaying multiple times but when I thought about a way of making it only display one it didnt display at all. I got a variable and set it to 0, There is a timer that sets it to 0 every 2 seconds. The function can only work when the value is 0 but as the function runs it adds sets the value to 1 so it cant run again until the timer sets it to 0

`

var messagees1 = 0;

function resetVariable() {
        messagees1 = 0;
    }
    setInterval(resetVariable, 2000);

socket.on('messageReceived', (data) => {
        if (data.senderr === userName && messagees1 == 0) {
            setChatMessages((prevMessages) => [
                ...prevMessages,
                { senderName: 'you', message: data.messagee },
            ]);
        } else if (data.sendpartner === userName && messagees1 == 0 ) {
            setChatMessages((prevMessages) => [
                ...prevMessages,
                { senderName: partner, message: data.messagee.trim() },
            ]);
        }
        messagees1 = 1

    });

`

I tried rearranging the positing of the if statements when the messagges is equal to zero but it didnt work. When i removed it, it displayed the text but multiple times. The main problem is the function is being called multiple times but I dont know how to fix that and I think this way that I am doing is easier

Why does signInWithPopup not work with shadcn/ui’s button?

I’m using Firebase with Next JS 14 and shadcn/ui. I was making a Sign In page and I used shadcn/ui’s button to create three buttons to sign in with Google, Github and Facebook. I added an onClick onto each of the buttons to sign in with Google, Github and Facebook respectively. I used the signInWithPopup function for all of the functions tied to the onClick‘s. However, when I click the buttons, nothing happens at all. A window doesn’t open or anything and it seems as if onClick isn’t working. Here is my code for the page:

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";

import {
  FaGoogle,
  FaGithub,
  FaFacebook
} from "react-icons/fa";

import { app } from "@/lib/firebase";
import {
  getAuth,
  signInWithPopup,
  GoogleAuthProvider,
  GithubAuthProvider,
  FacebookAuthProvider
} from "firebase/auth";

import { useRouter } from "next/router";

export default function Home() {
  const router = useRouter();

  const auth = getAuth(app);

  const withGoogle = () => {
    const provider = new GoogleAuthProvider();

    signInWithPopup(auth, provider)
      .then(() => {
        router.push("/home");
      })
      .catch((err) => {
        console.error("An error occured: " + err);
      });
  }

  const withGithub = () => {
    const provider = new GithubAuthProvider();

    signInWithPopup(auth, provider)
      .then(() => {
        router.push("/home");
      })
      .catch((err) => {
        console.error("An error occured: " + err);
      });
  }

  const withFacebook = () => {
    const provider = new FacebookAuthProvider();

    signInWithPopup(auth, provider)
      .then(() => {
        router.push("/home");
      })
      .catch((err) => {
        console.error("An error occured: " + err);
      });
  }

  return (
    <main>
      <div className="flex justify-center pt-64">
        <Card className="w-96">
          <CardHeader>
            <CardTitle> Sign In </CardTitle>
            <CardDescription>
              Sign in using one of these methods
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div>
              <Button onClick={withGoogle}>
                <FaGoogle className="mr-2 h-4 w-4" /> Sign In with Google
              </Button>
            </div>
            <div className="pt-3">
              <Button onClick={withGithub}>
                <FaGithub className="mr-2 h-4 w-4" /> Sign In with Github
              </Button>
            </div>
            <div className="pt-3">
              <Button onClick={withFacebook}>
                <FaFacebook className="mr-2 h-4 w-4" /> Sign In with Facebook
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </main>
  )
}

Thanks!

Utility Classes of Vuetify

Yo guys, i have a vuetify project that i need to change lnline style to utility classes (if possible)

font-size: 24px; font-weight :600

I saw the documentation that i only saw it set the size and weight without a value, such as text-h4 or font-weight-regular. May i know is it can change to utility classes if i want set the size and weight with value?

example code:

<span class="ma-0" style="color: var(--Gray-001, #7f7f7f); font-size: 22px; font-weight :600">Welcome to our shop </span>

How to add and remove background color of multiple boxes on click event

When I am clicking a box, background of page should change to the color of box (that is happening), but what I want is whichever box I clicked last , that box color should also change.
I am also achieving to add color to box that I clicked but when I clicked the next box the color on previous box is not removing. I want only one box(last clicked) to have color.

let h2 = document.querySelector("h2");
let p = document.querySelector("p");
let boxes = document.querySelectorAll(".box");
let body = document.body;

boxes.forEach((box) => {
  box.addEventListener("click", (e) => {
    let bgColor = e.target.id;
    body.style.backgroundColor = bgColor;

    if (e.target.id === "white" || e.target.id === "yellow") {
      h2.style.color = "black";
      p.style.color = "black";
    } else {
      h2.style.color = "white";
      p.style.color = "white";
    }

    // if(e.currentTarget.id === bgColor){
    //   box.style.backgroundColor = "#343434";
    // }else {
    //   box.style.backgroundColor = bgColor;
    // }
  }, false)
})
#main {
  width: 40%;
  text-align: center;
}

#boxes {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-block: 1.4rem;
  cursor: pointer;
}

.box {
  height: 100px;
  width: 100px;
  border: 2px solid black;
}

#boxes #grey {
  background-color: grey;
}

#white {
  background-color: white;
}

#blue {
  background-color: blue;
}

#yellow {
  background-color: yellow;
}
<div id="main">
  <h2>Color Switcher</h2>
  <div id="boxes">
    <div class="box" id="grey"></div>
    <div class="box" id="white"></div>
    <div class="box" id="blue"></div>
    <div class="box" id="yellow"></div>
  </div>
  <p>Click the boxes to change the background color of the page as box color</p>
</div>

The state of an array is not updating properly in a React function component [closed]

I have a functional component with an array state named setArray, which holds form controls. When I click the ‘Add New’ button, it successfully generates new controls and updates the array within the onClick function. However, when I call the same function in a loop within the onChange function, the array state does not update correctly..

This is my sample project
https://stackblitz.com/edit/node-nbgavp?file=README.md

I tried to introduce a small delay for updating the array, but it didn’t work

How to get Id from first API call, pass the Id to second API call as a parameter, display the first calls data and second calls related data?

I am sending an API request like the following to get a JSON array of collections objects. I am currently using a for loop to iterate through the array and get collections id.

https://www.eventbriteapi.com/v3/organizations/MyOrganizationIDHere/collections/?token=MyTokenHere

Once I have the collections id from the API call above, I am passing the collections id into the API call below to attempt getting related events to display right beneath the collection the events belong to.

"https://www.eventbriteapi.com/v3/collections/" +
  collectionResponse.collections[a].id +
  "/events/?time_filter=current_future&token=MyTokenHere";

At the very bottom of this post, you can see the JavaScript code I am currently using. I am not able to get the events to fall under the related collection. While searching Stack Overflow, I have found other posts that mention using the map function and promise.all. After looking at the documentation, I think that is where the answer is, but I don’t know how to incorporate that into my current code. I am finding it difficult to put together the code to make this work. I would appreciate any help!

$(document).ready(function () {
  $.getJSON(
    "https://www.eventbriteapi.com/v3/organizations/MyOrganizationId/collections/?token=MyToken",
    function (collectionResponse) {
      for (var a = 0, b = collectionResponse.collections.length; a < b; a++) {
        document.write(
          "COLLECTION | " + collectionResponse.collections[a].name,
        );

        $.getJSON(
          "https://www.eventbriteapi.com/v3/collections/" +
            collectionResponse.collections[a].id +
            "/events/?time_filter=current_future&token=MyToken",
          function (eventResponse) {
            for (var c = 0, d = eventResponse.events.length; c < d; c++) {
              document.write("EVENT | " + eventResponse.events[c].name.text);
            }
          },
          "jsonp",
        );
      }
    },
    "jsonp",
  );
});

Handling Error in React fetch when Result Array Exceeds 3 Elements

In React, I use the fetch function to receive a JSON file with the following content. However, if the result array has more than 3 elements, I encounter an error. Where could the issue be?

Content of the JSON file:

{
    "result": [
        {
            "open": 2428700,
            "high": 2442100,
            "low": 2427600,
            "close": 2439100,
            "change": 169000,
            "changePercent": 0.7,
            "date": "2023-11-25",
            "datePersian": "1402/09/04"
        },
        {
            "open": 2415500,
            "high": 2427600,
            "low": 2414200,
            "close": 2422200,
            "change": 78000,
            "changePercent": 0.32,
            "date": "2023-11-23",
            "datePersian": "1402/09/02"
        },
        {
            "open": 2421600,
            "high": 2430300,
            "low": 2413500,
            "close": 2414400,
            "change": -78000,
            "changePercent": -0.32,
            "date": "2023-11-22",
            "datePersian": "1402/09/01"
        },
        {
            "open": 2392700,
            "high": 2428000,
            "low": 2392700,
            "close": 2424300,
            "change": 212000,
            "changePercent": 0.88,
            "date": "2023-11-21",
            "datePersian": "1402/08/30"
        },
        {
            "open": 2423200,
            "high": 2423200,
            "low": 2387600,
            "close": 2403100,
            "change": -210000,
            "changePercent": -0.87,
            "date": "2023-11-20",
            "datePersian": "1402/08/29"
        }
    ]
}

React fetch:

  fetch('https://app.takhminzan.com/data.json')
    .then(response => response.json())
    .then(data => {
      console.log(data.result);
    })
    .catch(error => {
      console.error('Error:', error);
    });

Error:

Access to fetch at ‘https://app.takhminzan.com/data.json’ from origin ‘http://localhost:3000’ 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.

I changed the hosting to address this issue and removed access restrictions in the .htaccess file. However, the problem still persists.

Content of .haccess file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
</IfModule>

Is there any other AI integrations that could be done in website?

Openai chatbots and custom data chatbots are the only thing which website can include via API but is there anything else which we can implement? If not now then maybe in the future? In apps or website which doesn’t just use API and it is more complex that like making your own LLM and stuff. This is more of a discussion then a question

I tried looking for something more skillful but found nothing

Nodejs register hooks import

I am trying to create a hook to use ESM modules without .js extension. I am trying to use register() from node:modules, the idea is intercept the import and before search file put .js extension in run time. The example is:

// index.js
import { glob } from "glob";
import express from "express";
import { test } from "./second";
express()
console.log(test)
console.log(glob(''))

the hooks is:

//hook.js
export async function resolve(specifier, context, nextResolve) {
    console.log({
        specifier,
        context,
        nextResolve
    })
    if (typeof specifier === 'string' && specifier.startsWith('file://') && !specifier.endsWith('.js'))
        specifier += '.js'
    return nextResolve(specifier, context)

  // Take an `import` or `require` specifier and resolve it to a URL.
}

let a = 1
export const load = (url, context, loadDefaultAsync) => {
    if (typeof url === 'string' && url.startsWith('file://') && !url.endsWith('.js'))
        url += '.js'
  console.log(`loading ${url}`);
    console.log(context)
    console.log(a++)
  return loadDefaultAsync(url, context, loadDefaultAsync);
};

The file that I am trying to import:

//second.js
export const test = 'test'

And last, the register:

//loader.js
import { register } from 'node:module';

register('./hook.js', import.meta.url);

This is the script that I use to load the index:

node --loader ./src/hook.js src/index

When I run the file I have this error:

(node:17584) ExperimentalWarning: `--experimental-loader` may be removed in the future; 

instead use `register()`:
--import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("./src/hook.js", pathToFileURL("./"));'
(Use `node --trace-warnings ...` to show where the warning was created)
{
  specifier: 'file:///E:/Daniel-Pc/Dev-Pro/nodejs/js-stuff/src/index.js',
  context: {
    conditions: [ 'node', 'import', 'node-addons' ],
    importAssertions: {},
    parentURL: undefined
  },
  nextResolve: [AsyncFunction: nextResolve]
}
loading file:///E:/Daniel-Pc/Dev-Pro/nodejs/js-stuff/src/index.js
{ format: 'module', importAssertions: {} }
1
{
  specifier: 'glob',
  context: {
    conditions: [ 'node', 'import', 'node-addons' ],
    importAssertions: {},
    parentURL: 'file:///E:/Daniel-Pc/Dev-Pro/nodejs/js-stuff/src/index.js'
  },
  nextResolve: [AsyncFunction: nextResolve]
}
{
  specifier: 'express',
  context: {
    conditions: [ 'node', 'import', 'node-addons' ],
    importAssertions: {},
    parentURL: 'file:///E:/Daniel-Pc/Dev-Pro/nodejs/js-stuff/src/index.js'
  },
  nextResolve: [AsyncFunction: nextResolve]
}

node:internal/process/esm_loader:40
      internalBinding('errors').triggerUncaughtException(
                                ^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:Daniel-PcDev-Pronodejsjs-stuffsrcsecond' imported from E:Daniel-PcDev-Pronodejsjs-stuffsrcindex.js
    at new NodeError (node:internal/errors:406:5)
    at finalizeResolution (node:internal/modules/esm/resolve:233:11)
    at moduleResolve (node:internal/modules/esm/resolve:845:10)
    at defaultResolve (node:internal/modules/esm/resolve:1043:11)
    at nextResolve (node:internal/modules/esm/hooks:833:28)
    at resolve (file:///E:/Daniel-Pc/Dev-Pro/nodejs/js-stuff/src/hook.js:9:12)
    at nextResolve (node:internal/modules/esm/hooks:833:28)
    at Hooks.resolve (node:internal/modules/esm/hooks:278:30)
    at handleMessage (node:internal/modules/esm/worker:168:24)
    at Immediate.checkForMessages (node:internal/modules/esm/worker:117:28) {
  url: 'file:///E:/Daniel-Pc/Dev-Pro/nodejs/js-stuff/src/second',
  code: 'ERR_MODULE_NOT_FOUND'
}

Node.js v20.9.0

The idea is create a hook to add .js before import. Is that possible?

AJAX callback for file download including error handling

jsp

<button
  type="submit"
  id="btn_load"
  value="Search"
  class="btn btn-primary"
>Generate I-618</button>

js

$("#btn_load").click(function (e) {
  event.preventDefault();
  form = $("#bookList");
  var post_url = form.attr("action");
  let form_data = form.serialize();

  $.ajax({
    url: post_url,
    type: "POST",
    data: form_data,
    success: function (data, textStatus, jqX) {
      // Create a Blob from the data
      var blob = new Blob([data], { type: "text/plain" });

      // Create a link element
      var link = document.createElement("a");

      // Set the download attribute and create a URL for the file
      link.download = "your_filename.txt";
      link.href = window.URL.createObjectURL(blob);

      // Append the link to the document
      document.body.appendChild(link);

      // Trigger a click on the link to initiate the download
      link.click();

      // Remove the link from the document
      document.body.removeChild(link);
      $(".alert.alert-danger").text("Alert:success");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      // Handle errors by Displaying a message to user????
      $(".alert.alert-danger").text("Alert: Failure");
    },
  });
});

java

@RequestMapping(value = "/book.htm")
public ResponseEntity<InputStreamResource> bookselection(
        @ModelAttribute("books") Books book, Model model,
        HttpServletRequest request, BindingResult result) {
    List<InputStreamResource> listStream = new ArrayList<InputStreamResource>();
    String fileName = "book.txt"
    if (CollectionUtils.isNotEmpty(bookList)) {
        File file = File.createTempFile(fileName, ".txt");
        FileWriter interfaceFileWriter = new FileWriter(file);
        BufferedWriter interfaceBufferedWriter = new BufferedWriter(interfaceFileWriter);
        //write to file
        for (Book list : bookList) {
        interfaceBufferedWriter.write(list.getDelimitedRecord(delimiter, nullValue));
        }
        interfaceBufferedWriter.close();
        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        headers.setContentDispositionFormData(fileName + ".txt", fileName + ".txt");

        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        if (file != null && file.exists()) {
            listStream.add(resource);
            return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).headers(headers).body(resource);
        }
    }
    return null; //HOW TO RETURN ERROR STRING OR OBJECT??
}

if there is an error in Java code while writing to file, I would like return error string. Since the method returns ResponseEntity<InputStreamResource>, how do I handle sending error message from java to ajax.

  • How to return error message/error object from java ??
  • How to read error Ajax “error:” that was returned by server??