Connect Node.js back-end to React native front-end

I have a node.js back-end with Express and a native React front-end. The problem is that when I run a query from my front end, it gives me an error message saying Axios Network Failed. So I can’t connect my back to my front. However I have put the permissions of the cors (see below):

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());

const mysql = require('mysql');

const db = mysql.createConnection({
  host: 'localhost',
  user: '***',
  password: '***',
  database: '***',
});

app.use(express.json());

app.get('/users', (req, res) => {
  db.connect(function (err) {
    if (err) {
      throw err;
    }
    console.log('Connecté à la base de données MySQL!');
    db.query('SELECT * FROM users', function (err, result) {
      if (err) {
        throw err;
      }
      res.send(result);
    });
  });
});

app.post('/login', function (request, response) {
  let login = request.body.login;
  let mdp = request.body.mdp;
  if (login && mdp) {
    db.query(
      'SELECT * FROM users WHERE login = ? AND mdp = ?',
      [login, mdp],
      function (error, results, fields) {
        if (error) {
          throw error;
        }
        if (results.length > 0) {
          response.send(login);
        } else {
          response.status(404).send('Incorrect Username and/or Password!');
        }
        response.end();
      },
    );
  } else {
    response.status(404).send('Please enter Username and Password!');
    response.end();
  }
});

app.listen(8080, () => {
  console.log("Serveur à l'écoute");
});

Here is my request in my front-end :

const submit = async () => {
    if (!pseudo.trim() || !password.trim()) {
      alert('Nom ou mot de passe invalide');
      return;
    }
    const data = {
      login: pseudo,
      mdp: password,
    };
    try {
      const response = await axios.post(`${baseUrl}/login`, data);
      if (response.status === 200) {
        alert(`Vous êtes connecté en tant que ${pseudo} `);
      }
    } catch (e) {
      console.log(e);
    }
  };

If anyone has the solution, I’m a taker, thank you!

NextJS – TypeError: res.unstable_revalidate is not a function

I try to use a brand new feature released in NextJS v.12.1 https://deepinder.me/nextjs-on-demand-isr. The API itself works fine. I can reach it. But in exchange it returns 500 error that says res.unstable_revalidate is not a function.

This is the api endpoint:

// ./api/misc/revalidate

const revalidateCache = async (_, res) => {
    console.log(res.unstable_revalidate, 'TEST REVALIDATE');

    try {
        await res.unstable_revalidate('/');

        return res.json({ revalidated: true });
    } catch (err) {
        return res.status(500).send(`Error revalidating: ${err}`);
    }
};

export default revalidateCache;

This is the invoke:

// ./apps/client/services/server

export default function getRevalidate () {
    fetch('/api/misc/revalidate');
};

View layer that I call from:

// .src/pages/index.js

// ...some code here

const HomePage = ({ page, legacy }) => {
    const handleClick = () => {
        getRevalidate();
    };

    return (
        <div className={styles.homeRoot}>
            <button onClick={handleClick}>REVALIDATE</button>
        </div>
    );
};

Javascript Read input of a texture when I press Enter key

I have a problem with JS. I have a textarea with default text and I can write in the textarea, but if I want to save the content that I write in textarea in a variable in the js file, I cannot. I’ll show you some code:

let s = "";

function legge() {
 if (Event.key === "Enter") {
     s = document.getElementsByClassName("terminal").value;
     return s;
 }
 
}

console.log(legge());

This is the code, and in the HTML I have:

<textare class="terminal" onkeydown="legge()">macbook</textarea>

The console log return undefined, so it can’t read the input. Anyone can help me please? Thank you!

Accessing persisted alpine data in a second page

I have this alpine web page https://jsfiddle.net/0329pesx/

and i am using persist plugin in it.

This is how i am persisting the data

document.addEventListener('alpine:init', () => {
Alpine.data('sd', () => ({
        greeting: Alpine.$persist("hello world")
    }));
    
    Alpine.store('st', {
        darkMode: Alpine.$persist(true).as('on')
    })
});

and accessing it

 <div class="container" x-data="sd">
  Data:<h1 x-text="greeting"></h1> 
  </div>
  
    <div class="container" x-data> 
  Store: <strong x-text="$store.st.darkMode"></strong>
  </div>

How can i access the persisted in a second page?

Importing tesseract.js in chrome extensions

Im developing this chrome extensions and I want to use the tesseract.js library to recognize text in an image. Only im clueless on how to import the library. I am using manifest V3 so importing using the CDN link is not possible (as far as I read in the documentation). So I installed the library locally using npm --save, and then webpacked it with npx webpack, but I still cant get any off the functions imported.

I tried the options given by the tesseract.js documentation, which are:

import Tesseract from 'tesseract.js';

Tesseract.recognize(
  'https://tesseract.projectnaptha.com/img/eng_bw.png',
  'eng',
  { logger: m => console.log(m) }
).then(({ data: { text } }) => {
  console.log(text);
})

and

import { createWorker } from 'tesseract.js';

const worker = createWorker({
  logger: m => console.log(m)
});

(async () => {
  await worker.load();
  await worker.loadLanguage('eng');
  await worker.initialize('eng');
  const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
  console.log(text);
  await worker.terminate();
})();

But neither work, because tesseract.js is not a valid file according to the service worker. As said above, I also tried importing it using the CDN link, but because of the CSP regulations, chrome can’t import non-local libraries in Manifest V3 using links.
in this image you can see the file structure. I copied some of the tesseract files from the node_modules folder into the services folder for easier access.

Can anyone explain to me how I am supposed to import tesseract.js on a chrome extension. Apparently its not as easy as just using import Tesseract from 'tesseract.js';

Wait for user click then continue execution in React

I am making React Card game with hooks and all that. But I can’t figure out how to implement wait for user click when certain condition is met (when is turn on human player for example). I need it to work on certaint buttons (cards), not global window click. I tried with async await and event listeners but can’t get it to work (event listener not reconized, not sure if it works in React). If someone could help me out with template on how to do that.
Thank you for the help in advance. Code sample is below

export function playTurn(...players) {
  let cardsThrown = 0;

// for example if lastWinner or secondPLayer===human wait for on click on "classname"

  whoPlaysFirst(...players);

  let lastWinner = lastTurnWinner(...players);

  const { hand: lastTurnWinnerHand } = lastWinner;

  lastWinner.currentCard = lastWinner
    .playCard(sample(lastTurnWinnerHand))
    .shift();
  Game.winningSuit = lastWinner.currentCard.suit;
  cardsThrown += 1;
  console.log(lastWinner.currentCard);

  while (cardsThrown !== 4) {
    let secondPlayer = nextPlayer(Game.lastPlayer);
    secondPlayer.currentCard = secondPlayer
      .playCard(sample(secondPlayer.hand))
      .shift();
    cardsThrown += 1;
    console.log(secondPlayer.currentCard);

    lastWinner = winningCard(lastWinner, secondPlayer); //Pobjednik ostaje
    Game.lastPlayer = secondPlayer;
  }
  console.log("Pobjednicka karta je: ", lastWinner.currentCard);

  nextTurn(lastWinner, ...players);
}

“Firebase: Error (auth/invalid-value-(email),-starting-an-object-on-a-scalar-field-invalid-value-(password),-starting-an-object-on-a-scalar-field).”

I am getting error on email/Password authentication using firebase. When i clicks on sign up button the following error occurs “Firebase: Error (auth/invalid-value-(email),-starting-an-object-on-a-scalar-field-invalid-value-(password),-starting-an-object-on-a-scalar-field).”

Javascript Code

How to pass uploaded file (multi-part) in njs nginx to chain request

I’am trying to pass uploaded file from first request to second one, scenario is this : i make a request with a file in form-data , after validation i get some response then post file and response to second request.

Thing i did are :

1-try to get file with r.requestBuffer and put in in body.

2-try to conver r.requestText to a file with fs.readFileSync then put it in body.

var fs = require("fs");
async function chain(r) {
  var engine_uri = r.uri;
  var args = r.args;
  var body = r.requestBuffer; // fs.readFileSync(r.requestBuffer); // here i need to get file and send it to second request

  r.headersOut["Content-Type"] = "application/json";
  r.headersOut["Access-Control-Allow-Origin"] = "*";
  r.headersOut["Access-Control-Allow-Methods"] = "*";
  r.headersOut["Access-Control-Max-Age"] = "3600";
  r.headersOut["Access-Control-Allow-Headers"] = "*";

  if (r.method == "OPTIONS") {
    r.return(200);
  }

  r.subrequest("/validation", { method: "POST" }) //first request
    .then((Response) => {

      if (Response.status <= 200) {
        return JSON.parse(Response.responseText);
      } else {
        r.return(Response.status, JSON.stringify(Response));
      }
    })
    .then((ResponseB) => {      

      r.subrequest("/persistance" + engine_uri, { //second request
        args: `UserID=${ResponseB.UserID}&AccountID=${
          ResponseB.AccountID
        }&Username=${ResponseB.Username}&System=${
          ResponseB.System
        }&${jsonToQueryString(args)}`,
        method: r.method,
        body: body, // i need to transferre file to this request
      }).then((resp) => {
        r.return(resp.status, resp.responseText);
      });
    })
    .catch((e) => {
      r.return(200, e);
    });
}

Also i put client_body_buffer_size 100M; to default.conf

js_import http.js;
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    proxy_read_timeout 300;
    proxy_connect_timeout 300;
    proxy_send_timeout 300; 
    subrequest_output_buffer_size 5000k;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }


    location ~ ^/.*$ {
      js_content http.chain;
    }

    location ^~ /persistance/ {    
       proxy_pass http://192.168.2.76:5001/;      
    }

    location ^~ /AlphaCore/ {    
       proxy_pass http://192.168.2.76:8088;      
    }

    location ^~ /AlphaComm/ {
      js_content http.alpha_comm;
    }

    location ^~/AlphaCommRequest/ {
      rewrite ^/AlphaCommRequest/(.*)$ /$1 break;
      proxy_pass http://192.168.2.76:8586/AlphaComm;
    }


    location = /validation {
       proxy_pass http://192.168.2.76:8088/AlphaCore/v1/user/validation;
    }

    client_body_buffer_size 100M;

}

How can I conditionally render my Header above this.props.children? [duplicate]

This is my app.js where all the routes

<Layout>
      <Router>
        <Routes>
          <Route exact path="/" element={<Home />} />
          <Route element={<PrivateRoute />}>
            <Route exact path="/dashboard" element={<Dashboard />} />
            <Route exact path="/video" element={<Video />} />]
          </Route>
          <Route exact path="/login" element={<Login />} />
       </Routes>
      </Router>
</Layout>

This is my loyout component

export default class Layout extends Component {
  render() {
    return (
      <div>
        <Router>
          <Header />
        </Router>
        {this.props.children}
      </div>
    );
  }
}

So I have two questions

  1. I could able to use useNavigate in Header since it was not in the surrounded with the <Router> but after using it is working. So is there any better way of doing this?
  2. I need to render conditionally because I don’t want it to be on the login page.

Kindly help!!!

Opacity and Colors in React Native Chart Kit

lmao, i know this is stupid and simple but i just can’t find the right question to look it up on google, so here it is

the syntax that i want to follow but instead of using RGB values, i want to use my defined color from another class

enter image description here

im confused, how do you take the opacity and put it next to each other kinda(?), im trying to make transparent as well

enter image description here