Rewriting URL using Locale in Next JS 13

I am trying to rewrite the url based on the locale retrieved from my middleware.js, however, the url is not rewritten and returns a page-not-found 404. However, when I go to “localhost:3000/en” for example I get the correct response and everything works as expected. What am I missing here?

middleware.js

import { NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";

let locales = ["en", "ka", "ru"];
export let defaultLocale = "en";

function getLocale(request) {
  const headers = new Headers(request.headers);
  const acceptLanguage = headers.get("accept-language");
  if (acceptLanguage) {
    headers.set("accept-language", acceptLanguage.replaceAll("_", "-"));
  }

  const headersObject = Object.fromEntries(headers.entries());
  const languages = new Negotiator({ headers: headersObject }).languages();
  return match(languages, locales, defaultLocale);
}

export function middleware(request) {
  let locale = getLocale(request) ?? defaultLocale;
  const pathname = request.nextUrl.pathname;

  const newUrl = new URL(`/${locale}${pathname}`, request.nextUrl);

  // e.g. incoming request is /products
  // The new URL is now /en/products
  return NextResponse.rewrite(newUrl);
}

export const config = {
  matcher: ["/((?!_next|api|favicon.ico).*)"],
};

file structure

src
-app
--[lang]
---(public)
----layout.jsx
----page.jsx

UPDATE

the problem appears to be having everything in my src folder. Moving my app directory into the root seems to fix the problem? Why would this be causing an issue?

How to call a list from app.js to a component in react js

I am trying to set a state in a component and transfer that list from one component to another. But getting console error as List.map() is not a function!

I am trying to get webpage as enter image description here using react js

App.js :

import GoogleSuggestions from './components/GoogleSuggestions'

import './App.css'

const suggestionsList = [
  {id: 1, suggestion: 'Price of Ethereum'},
  {id: 2, suggestion: 'Oculus Quest 2 specs'},
  {id: 3, suggestion: 'Tesla Share Price'},
  {id: 4, suggestion: 'Price of Ethereum today'},
  {id: 5, suggestion: 'Latest trends in AI'},
  {id: 6, suggestion: 'Latest trends in ML'},
]

const App = () => <GoogleSuggestions suggestionsList={suggestionsList} />

export default App

components/GoogleSuggestions :

// Write your code here
import {Component} from 'react'

import SuggestionItem from '../SuggestionItem'

import './index.css'

class GoogleSuggestions extends Component {
  state = {suggestionsList: this.props, searchInput: ''}

  showoptions = event => {
    this.setState({searchInput: event.target.value})
  }

  render() {
    const {suggestionsList, searchInput} = this.state
    console.log(typeof suggestionsList)
    return (
      <div className="bg-container">
        <img
          className="googleLogo"
          src="https://assets.ccbp.in/frontend/react-js/google-logo.png"
          alt="google logo"
        />
        <div className="input-container">
          <div>
            <img
              className="search-icon"
              src="https://assets.ccbp.in/frontend/react-js/google-search-icon.png"
              alt="search icon"
            />
            <input
              type="search"
              value={searchInput}
              onClick={this.showoptions}
              className="input"
              placeholder="Search Google"
            />
          </div>
          <ul className="ul-cont">
            {suggestionsList.map(eachItem => (
              <SuggestionItem itemDetails={eachItem} key={eachItem.id} />
            ))}
          </ul>
        </div>
      </div>
    )
  }
}

export default GoogleSuggestions

SuggestionItem


// Write your code here 
import {Component} from 'react' 
import './index.css'  
class SuggestionItem extends Component {
   render() {
     const {itemDetails} = this.props
     const {id, suggestion} = itemDetails
     return (
       <li>
         <div className="Item-cont">
           <p>{suggestion}</p>
           <img
             src="https://assets.ccbp.in/frontend/react-js/diagonal-arrow-left-up.png"
             alt="arrow"
           />
         </div>
       </li>
     )
   }
}
export default SuggestionItem

I am expecting to send list to component/GoogleSuggestions but getting as object.

npm ERR! code 1 during installation of opentelemetryio – Error in hugo-extended postinstall.js

enter image description hereI’m encountering an error while setting up opentelemetryio’s development environment (https://github.com/open-telemetry/opentelemetry.io)(https://github.com/open-telemetry/opentelemetry.io/blob/main/CONTRIBUTING.md) (https://github.com/open-telemetry/opentelemetry.io/blob/main/package.json)using npm. Here’s the output:

npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-url#deprecated
… (other deprecation warnings)
npm ERR! code 1
npm ERR! path /home/rafe/Desktop/opentelemetryio/node_modules/hugo-extended
npm ERR! command failed
npm ERR! command sh -c node postinstall.js

npm ERR! A complete log of this run can be found in: /home/rafe/.npm/_logs/2024-03-10T06_00_26_721Z-debug-0.log

System Information:

OS: Ubuntu 23.10
npm version: 10.5.0
node version: v20.11.1

Any help will be highly appreciated. Thank You in advance.

The error seems to originate during the postinstall.js script execution within the hugo-extended package. I’ve tried the following troubleshooting steps (if applicable):

Cleared npm cache (npm cache clean --force)
Reinstalled dependencies (npm install)

I am expecting to setup the development environment of this website https://opentelemetry.io/

The codebase of this website can be found here –> https://github.com/open-telemetry/opentelemetry.io

TypeError: Named parameters can only be passed within plain objects, while trying to handle Sqlite errors using ES6 arrow functions

I have some working code to manipulate a Sqlite database written in this notation (I think ES5?):

try {
    const cols = Object.keys(data).join(", ");
    const placeholders = Object.keys(data).map(x => "$" + x).join(", ");
    const stmt = db.prepare(`
      INSERT INTO ` + table + ` (` + cols + `) 
      VALUES (` + placeholders + `)`);
    stmt.run(data);
} catch (err) { 
    // some reporting and handling
}

Where the values to populate the SQL statement come from a JS object (data) passed on earlier.

I would like to refactor this to use ES6 and replace the try...catch block with arrow functions. I found some examples (here and here) but they use a different syntax, where the SQL command is executed directly with the .run() method, instead of using .prepare() as I have in my code.

However, when I try to apply an arrow function directly to my code

const cols = Object.keys(data).join(", ");
const placeholders = Object.keys(data).map(x => "$" + x).join(", ");
const insert_stmt = db.prepare(`
  INSERT INTO ` + table + ` (` + cols + `) 
  VALUES (` + placeholders + `)`);
insert_stmt.run(data, (err) => {
    if (err.message === "some error") { 
       // handle the error
    }
});

I get the error

TypeError: Named parameters can only be passed within plain objects

From what I could understand, this is probably a syntax error? Which I think means with the new notation I’m not passing the values within the data object correctly.

What are the best practices in a situation like this? Should I abandon the .prepare() syntax and go with the examples in the webpages I linked?

javascript file is getting marked as “malware” by windows defender

I was trying to download this file off of github because I wanted to try to learn some javascript https://github.com/rohan-paul/Awesome-JavaScript-Interviews/blob/master/Javascript/ES6-Array-Helper-Methods/destructuring.js

it gets marked as a virus by windows defender
This is what windows defender marks the javascript file as malware
Anyone know why this is happening to me?

If I turn off windows defender and download the file it cant mark it as malware but if I turn it back on and open the javascript file it removes it

CORS Policy always blocks my access to azure API from my react app, while it is working with Postman

I have a GET API from azure that generates a token when the page loads. and I need to connect it with my react app. I tried the API first on Postman, everything worked successfully and I got a generated token. After that, I used axios to connect with the API in my react app. But everytime I get this error message that says “Access to XMLHttpRequest at ‘https://myTokenAPI/api/[email protected]’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

{
“message”: “Network Error”,
“name”: “AxiosError”,
“stack”: “AxiosError: Network Errorn at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=03d0e2b6:1450:14)n at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=03d0e2b6:1780:41)”,
“config”: {
“transitional”: {
“silentJSONParsing”: true,
“forcedJSONParsing”: true,
“clarifyTimeoutError”: false
},
“adapter”: [
“xhr”,
“http”
],
“transformRequest”: [
null
],
“transformResponse”: [
null
],
“timeout”: 0,
“xsrfCookieName”: “XSRF-TOKEN”,
“xsrfHeaderName”: “X-XSRF-TOKEN”,
“maxContentLength”: -1,
“maxBodyLength”: -1,
“env”: {},
“headers”: {
“Accept”: “application/json, text/plain, /“,
“tenant”: “secret value that I can’t show”,
“Ocp-Apim-Subscription-Key”: “secret value that I can’t show”
},
“method”: “get”,
“url”: “https://myTokenAPI/api/[email protected]
},
“code”: “ERR_NETWORK”,
“status”: null
}

my react code:
I’m sorry about showing the endpoint and the header values

import { useState, useEffect } from "react";
import { Navbar, Secondtransition } from "./index";
import axios from "axios";

export default function Dailyform() {
  const [transfared, setTransfared] = useState(false);


  useEffect(() => {
    setTimeout(() => setTransfared(true), 1000);

    axios
      .get(
        `https://myTokenAPI/api/[email protected][email protected]`,
        {
          headers: {
            tenant: "secret value that I can't show",
            "Ocp-Apim-Subscription-Key": "secret value that I can't show",
          },
        }
      )
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => console.error(err));
  }, []);

  return (
    <div className="daily-form w-full min-h-[100vh] relative">
      <Navbar />
      <div className="page-content w-full flex-col items-center justify-center text-center">
        <h1 className="text-4xl text-[#fff] font-yeseva py-10">
          Daily Sales Upload Page
        </h1>
        <form
          action=""
          className="flex flex-col space-y-10 w-full items-center justify-center"
        >
          <input
            type="text"
            className="w-1/2 py-5 border-b-[1px] border-[#fff] px-3 bg-[rgba(255,255,255,0.1)] placeholder:text-[#fff] text-[#fff]"
            placeholder="Enter Your Name"
          />
        </form>
      </div>
      <Secondtransition transfared={transfared} />
    </div>
  );
}

1- I tried to contact with the IT of the company that made the API, and he said that it’s working with others normally.

2- I tried to use https with my localhost server using mkcert, and nothing changed

3- I tried to upload the app on a real domain, sorry for not sharing it because it contains private information, and agian nothing changed.

4- I tried to use JavaScript fetch, agian the same error.

5- I tried to use Jquery, I wasn’t sure about the correctness of the code, but the same error appeared.

6- i tried to take the code out of the useEffect react hook, and nothing changed, the same error 🙁

The error “Uncaught TypeError TypeError: Cannot set properties of null”

This error is showing up only when I have 2 different files for html and js. even if i add ” document.addEventListener(‘DOMContentLoaded’, function() {
countEl.addEventListener(“click”, increment);
});”

Given below are the code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js"></script>
    //<link rel="stylesheet" href="./index.css">
</head>

<body>
    <h1>People entered:</h1>
    <h2 id="count-el">0</h2>
    <button id="increment-btn" onclick="increment()">INCREMENT</button>
    <button id="save-btn" onclick="save()">SAVE</button>
    
</body>

</html>



let count = 0;
      let countEl = document.getElementById("count-el")

        function increment() {
            count = count + 1;
            countEl.innerText = count;

        }
        increment();
        function save(){
            console.log(count);
        }

        document.addEventListener('DOMContentLoaded', function() {
            countEl.addEventListener("click", increment);
        });

          

it either shows error for the line “countEl.innerText = count;” or for “INCREMENT” and “SAVE” button, the error shows for button if i remove listners is “Uncaught ReferenceError: increment is not defined” i want to make this work in two different file ie, html and js two seperate files. Refer to the image as well.

enter image description here
when click on increment button every time the count should be added +1. and when click on save the count should stop with the last cilcked number.

tensorflow no output (tf beginner level)

I’m having a problem with my tensorflow code, it won’t output anything about the prediction and losses of my model. here’s the code

const model = tf.sequential();



model.add(tf.layers.dense({ units: 4, inputShape: [3], activation: 'sigmoid' }));

model.add(tf.layers.dense({ units: 3, activation: 'sigmoid' }));



model.compile({

  optimizer: tf.train.sgd(0.1),

  loss: "meanSquaredError",

});



const input = tf.tensor2d([

  [1,0],

  [0,0],

  [0,0],

]);

const target = tf.tensor2d([

  [5],

  [0],

  [0],

]);



train().then(() => {

  console.log("training complete");

  const prediction = model.predict(input);

  prediction.print();

});



async function train() {

  for (let i = 0; i < 100; i++) {

    const response = await model.fit(input, target, {

      epochs: 20,

      shuffle: true,

    });

    console.log(response.history.loss[0]);

  }

}

I’ve tried tweaking, put random values in the arrays (inputs outputs) but I never got my expected results! which is just some loss value and the goal data

can you please see what’s wrong with my code?

thanks

Live Update in JavaScript

I have a random increase for a bunch of variables, I used setIntervel() to have something like a live update for the variables but they don’t seem to update:

    const no= document.getElementById("no");
    const ni= document.getElementById("no");
    const nu= document.getElementById("no");
    const ny= document.getElementById("no");
    const nt= document.getElementById("no");
    const visit = document.getElementById("visited");
    let a = sessionStorage.getItem("a") ? parseInt(sessionStorage.getItem("a")) : 1;
    let b = sessionStorage.getItem("b") ? parseInt(sessionStorage.getItem("b")) : 1;
    let x = sessionStorage.getItem("x") ? parseInt(sessionStorage.getItem("x")) : 1;
    let y = sessionStorage.getItem("y") ? parseInt(sessionStorage.getItem("y")) : 1;
    let z = sessionStorage.getItem("z") ? parseInt(sessionStorage.getItem("z")) : 1;
    let display;

    no.onclick = function(){
        sessionStorage.setItem("a", a + 1);
        window.location.href = "no.html";
    }

    ni.onclick = function(){
        sessionStorage.setItem("b", b + 1);
        window.location.href = "ni.html";
    }

    nu.onclick = function(){
        sessionStorage.setItem("x", x + 1);
        window.location.href = "nu.html";
    }

    ni.onclick = function(){
        sessionStorage.setItem("y", y + 1);
        window.location.href = "ny.html";
    }

    nt.onclick = function(){
        sessionStorage.setItem("z", z + 1);
        window.location.href = "nt.html";
    }

    function update(){
        if(a > b && a > x && a > y && a > z){
            display = "Popular Now: no";
            visit.textContent = display;
        }
        else if(b > a && b > x && b > y && b > z){
            display = "Popular Now: ni";
            visit.textContent = display;
        }
        else if(x > a && x > b && x > y && x > z){
            display = "Popular Now: nu";
            visit.textContent = display;
        }
        else if(y > a && y > b && y > x && y > z){
            display = "Popular Now: ny";
            visit.textContent = display;
        }
        else if(z > a && z > b && z > x && z > y){
            display = "Popular Now: nt";
            visit.textContent = display;
        }
    }

    setInterval(() => {
        let i = Math.floor(Math.random() * 5 + 1);

        if (i === 1) {
            sessionStorage.setItem("a", parseInt(sessionStorage.getItem("a") || 0) + 1);
        } else if (i === 2) {
            sessionStorage.setItem("b", parseInt(sessionStorage.getItem("b") || 0) + 1);
        } else if (i === 3) {
            sessionStorage.setItem("x", parseInt(sessionStorage.getItem("x") || 0) + 1);
        } else if (i === 4) {
            sessionStorage.setItem("y", parseInt(sessionStorage.getItem("y") || 0) + 1);
        } else {
            sessionStorage.setItem("z", parseInt(sessionStorage.getItem("z") || 0) + 1);
        }

        update();
    }, 5000);

The live update should occur right after the values increase meaning that it isn’t using outdated values, yet I have to manually reload the page to see the change, and if anybody can offer a more random way of adding to the values I would like to know it, also don’t mind the weird variable and button names, it is not something I would like to share online, Thanks.

I was expecting a live update for the popular now part

drawing app for create draw triangle tool

Now I have the below code for me to draw the triangle, but the shape expand direction is not what I want. I would like to have the equilateral triangle expand symmetrically from the mouse position. How should I adjust this?

function DrawTriangle() {
    this.icon = "assets/triangle.jpg";
    this.name = "DrawTriangle";
    this.color = "black"; // Default color is black

    var startTriX = -1;
    var startTriY = -1;
    var drawingTri = false;

    this.draw = function() {
        if (mouseIsPressed) {
            if (startTriX == -1) {
                startTriX = mouseX;
                startTriY = mouseY;
                drawingTri = true;
                loadPixels();
            } else {
                updatePixels();
                stroke(this.color); // Set the stroke color to the selected color
                strokeWeight(5);
                // Calculate the height of an equilateral triangle
                var triHeight = (mouseX - startTriX) * Math.sqrt(3) / 2;
                // Draw an equilateral triangle using the mouse position as the third vertex
                triangle(startTriX, startTriY, mouseX, mouseY, startTriX + (mouseX - startTriX) / 2, startTriY + triHeight);
                noFill();
            }
        } else if (drawingTri) {
            drawingTri = false;
            startTriX = -1;
            startTriY = -1;
        }
    }
}

Cookie is destroyed once I switch the page

My program logs in (in login.html) and the express session cookie is created. Once the page is switched to index.html, the cookie is lost. I am using the live port extension running of port 5500 vscode and I am using node with mongo running on port 3000.

Here is the code snippet.


  const corsOptions = {
    origin: 'http://127.0.0.1:5500', // Set to your frontend's origin
    credentials: true, // To allow cookies and sessions
  };


const app = express();
app.use(cors(corsOptions));
app.options('*', cors(corsOptions));
app.use(express.json());
app.use(cookieParser());
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: true,
  cookie: {
    path: '/',
    httpOnly: false, //cahnge later to true
    secure: false, // For development. Use 'true' for production with HTTPS.
    sameSite: 'none',
    maxAge: 1000 * 60 * 60 * 24 * 365
  }
}));

I have tried adding the path, changing the sameSite to Lax, changing the max age, adding credentials. To add on, my back end works perfectly fine with Thunder Client. The cookie is stored and I can use a post to retrieve the user data.

IOREDIS: How to load balance read queries when there are multiple slaves to a single master

I am using Ioredis client in JS for redis cluster. When I use scaleReads: “slave”, read queries are sent to a slave node. But when there multiple slave nodes for a single key, then a random node is choosen.

How do I load balance the read requests to all the slaves for a master or is this concept of choosing a random node enough to distribute load?
Please suggest some ideas