Fetch() not working with React and Laravel

I use a React template in frontend and a laravel in backend, I want to get data from URL using fetch().

In controller I do a test like that:

    public function index()
{

return response()->json([
'name' => 'Abigail',
'state' => 'CA',
]); 
}

Web.php :

 Route::get('/home', [PostController::class,'index']); //http://localhost:8000/home

in frontend I called the url in index.jsx like that :

  ......
  import React, { useEffect, useState } from "react";

   const TeamStats = () => {

   const [users, setUsers] = useState([]);

useEffect(() => {
    const url = "http://localhost:8000/home";
  
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const {results} = json;
        // Only put the results in state, ie, the actual users array
        setUsers(results);
      } catch (error) {
        console.log("error", error);
      }
    };
  
    fetchData();
  }, []);

const {theme} = useThemeProvider();
const {width} = useWindowSize();

const data = [
    {label: 'Wins', shortLabel: 'W', value: 17},
    {label: 'Draws', shortLabel: 'D', value: 29},
    {label: 'Losses', shortLabel: 'L', value: 74},
]


return (
    <Spring  ......
     
  ......
  .....
        
                <h2 className={`${styles.club} text-20 text-black text-overflow`}>Brussia</h2>
                {users && users.map((user) => (
                <h4 className="text-black text-overflow">{user.name}</h4>
                ))}
            </div>
            <div className="d-flex flex-wrap g-20">
                {
                    data.map((item, index) => (
                        <StatsBadge key={index}
                                    label={width >= 1024 ? (width >= 1500 && width < 1920 ? item.shortLabel : item.label) : item.shortLabel}
                                    value={item.value}/>
                    ))
                }
            </div>
        </div>
    </Spring>
)
}

export default TeamStats

After correcting all errors, I can’t get any result in frontend page just empty, also I can’t change the code because is a template already created, I mean I can’t change const TeamStats = () => { by function()?

NextJS Lighthouse Best Practices: Properly defines charset Error

I get this error on my blog page:
Properly defines charset Error! A character encoding declaration is required. It can be done with a tag in the first 1024 bytes of the HTML or in the Content-Type HTTP response header. Learn more about declaring the character encoding.

I do not get this error on my index page and other pages despite having <meta charset="UTF-8" /> on the page.

My _document.js:

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html lang="ja">
        <Head>
        <meta charset="UTF-8" />

        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

The error goes away when I reduce the amount of data that is returned from the getserversideprops on my blog page. Does this relate with the Properly defines charset error?

If it does, I would return some data from the client side but that would affect the SEO.

How can I resolve this issue?

I tried reducing the amount of data returned from the MySQL Database in the getserversideprops and the error disappeared.

Session data not persisted across requests – Laravel/Inertia

I am trying to save data in session on a post request, which then redirects to another page

try {
    $tenant = Tenant::where('email', '=', $request->input('email'))->firstOrFail();
} catch(Throwable $e) {
    return redirect(route('portal.login'))->withErrors(['email' => 'We cannot find any tenant associated with this email address']);
}
    
$this->sendInvite($tenant);

$request->session()->put('tenant', $tenant);
$request->session()->save();

return redirect(route('portal.login.invite'));

I have confirmed that the session data has been stored. Below is a DD of the session

array:4 [▼ // app/Http/Controllers/PortalController.php:55
  "_token" => "hsD4WKNkqFGsVnOMfPhsDcbpj31UcW10ATyFvOQ2"
  "_flash" => array:2 [▶]
  "_previous" => array:1 [▶]
  "tenant" => AppModelsTenant {#1381 ▶}
]

But when I try and validate for this data on the redirect route, the session data is missing

if (!$request->session()->exists('tenant')) {
    dd(session()->all());
    return redirect(route('portal.login'));
}

Session data:

array:3 [▼ // app/Http/Controllers/PortalController.php:72
  "_token" => "hsD4WKNkqFGsVnOMfPhsDcbpj31UcW10ATyFvOQ2"
  "_flash" => array:2 [▶]
  "_previous" => array:1 [▶]
]

Anybody have any ideas why this might be happening? I can share more information upon request

Parameterize tests to user with different setting each time

I’m trying to run the same tests for different user settings I have,
My implementation is to loop through the user setting array and update the user setting before the tests run…
the issue I face is due to the asynchronous nature of the playwright tests and the way JavaScript handles loops, all my tests always run with the last ‘tier2’ user settings.
any suggestion on how to approach that test case? (I want to be able to run the tests in parallel)

here is a code example:

import {test} from '@playwright/test'
import updateUserSettings from '../utils/updateUserSettings'
import checkApiPermissions from '../helpers/checkApiPermissions'


const userSettingArray = ['admin', 'tier1', 'tier2'];
const endpointArray = ['users', 'settings', 'message', 'image', 'video', 'search', 'about']

async function testHelper() {
    for( const settings of userSettingArray) {
        await updateUserSettings(settings);

        for(const endpoint of endpointArray){
            test(`test ${settings} settings`, ()=> {
                checkApiPermissions(settings, endpoint);
            });
        }
    }
}

testHelper().catch(console.error)

I tried to run the tests in parallel for each user settings

Promise.All undefined is not iterable, why response data is not iterable

I want to set both commission and dividends data before loading the page/component. Error I receive is undefined is not iterable (cannot read property Symbol(Symbol.iterator))
React Component

const [totalCommission, setTotalCommission] = useState(0)
const [totalDividends, setTotalDividends] = useState(0)
const accountFilter = useSelector((state) => state.accountFilter.value)
useEffect (() => {
    Promise.all([
        fetch('http://localhost:8000/api/overview/commission'),
        fetch('http://localhost:8000/api/overview/dividends')
    ])
    .then(([commissionRes, dividendsRes]) => {
        Promise.all([commissionRes.json(), dividendsRes.json()]) 
    })
    .then(([commissionData, dividendsData]) => {
        console.log(commissionData);
        console.log("DIVIDENDS")
        console.log(dividendsData)
        setTotalCommission(commissionData);
        setTotalDividends(dividendsData);
    });
    
},[])

Data Function Returns

return Response({'totalAmount': totalDividendAmount}, status=status.HTTP_200_OK)  

and

return Response({'totalAmount': totalCommissionAmount}, status=status.HTTP_200_OK) 

React component not displaying fetched data due to incorrect URL construction (404 Not Found)

I’m working on a React component to fetch data from a Django REST Framework API using Axios. However, the component isn’t displaying the fetched data, and I’m encountering a 404 Not Found error in the network tab.

Post.jsx

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Post({ postId }) {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
console.log(postId)
  useEffect(() => {
    const fetchPost = async () => {
      setIsLoading(true);
      const url = `http://127.0.0.1:8000/myapi/posts/${postId}`;
      console.log('Constructed URL:', url);
      try {
        const response = await axios.get(`http://127.0.0.1:8000/myapi/posts/${postId}`); 
        setData(response.data);
      } catch (error) {
        setError(error);
        console.error('Axios request error:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPost();
  }, [postId]);


  return (
    <div>
      {isLoading ? (
        <p>Loading post...</p>
      ) : error ? (
        <p>Error fetching post: {error.message}</p>
      ) : (
        <article>
          <h2>{data.title}</h2>
          <p>{data.content}</p>
          <p>Author: {data.author.username}</p> // Assuming author data is included
          <p>Categories: {data.categories.map((category) => category.name).join(', ')}</p> // Assuming categories data
          <p>Tags: {data.tags.map((tag) => tag.name).join(', ')}</p> // Assuming tags data
          {/* Additional elements for comments, etc. */}
        </article>
      )}
    </div>
  );
}

export default Post;

API Response (when accessed directly):

HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 1,
    "categories": [
        {
            "id": 1,
            "name": "test"
        }
    ],
    "tags": [
        {
            "id": 1,
            "name": "test"
        }
    ],
    "title": "Post1",
    "content": "asdijfoiajfoajsfopajsfpoasjfopajdfpoaodjfpadfiapoidfjapdfoajsdfpoaispdfajsdfopasfiojapdfjaopssdfjpajdfoiajpsfaf",
    "created_at": "2024-01-04T15:57:20.472070Z",
    "author": 1
}

App.js

import React from 'react';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Posts from './components/Posts/Posts';
import Post from './components/Post/Post';
import {BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import './Global.css';

function App() {
  return (
    <Router>
      <Header />
      <main>
        <Routes>
          <Route path="/" element={<Posts />} />
          <Route path="/posts/:postId" element={<Post />} />
        </Routes>
      </main>
      <Footer />
    </Router>
  );
}

export default App;

Troubleshooting Steps:

Verified API Response: The API endpoint returns the expected data structure when accessed directly.
Checked Network Requests:
The request URL in the network tab is http://127.0.0.1:8000/myapi/posts/undefined.
This is causing a 404 Not Found error.
Inspected State Values: The data state is not being populated due to the failed request.

Additional Information:

React version: [email protected]
Axios version: “axios”: “^1.6.4”,
Django REST Framework version: djangorestframework==3.14.0
Browser and version: Chrome Versión 120.0.6099.129
What could be causing the incorrect URL construction, and how can I ensure the correct postId is passed to the component?

Any guidance or insights would be greatly appreciated!

Restoring parentheses in a string

There is a source string with brackets, then actions are performed on it (which I cannot influence) and I get an array of substrings, unfortunately the brackets are lost in them.

I need to restore the brackets in each element of the array.

For example I have a string:

"=SUM((A1+B1)/C1,SUM(A1:C3,D6*(D12-E12)))"

(I work with Excel and all strings will be in the format of such formulas.)

After processing, I get an array:

[
   {
      "name":"SUM(A1+B1/C1,SUM(A1:C3,D6*D12-E12))",
      "depth":0
   },
   {
      "name":"A1+B1/C1",
      "depth":1
   },
   {
      "name":"A1+B1",
      "depth":2
   },
   {
      "name":"A1",
      "depth":3
   },
   {
      "name":"B1",
      "depth":3
   },
   {
      "name":"C1",
      "depth":2
   },
   {
      "name":"SUM(A1:C3,D6*D12-E12)",
      "depth":1
   },
   {
      "name":"A1:C3",
      "depth":2
   },
   {
      "name":"D6*D12-E12",
      "depth":2
   },
   {
      "name":"D6",
      "depth":3
   },
   {
      "name":"D12-E12",
      "depth":3
   },
   {
      "name":"D12",
      "depth":4
   },
   {
      "name":"E12",
      "depth":4
   }
]

(I can’t change the array creation function.)
In this array, some elements in the name property have lost parentheses, I need to restore them.

I need result like:

[
   {
      "name":"SUM(A1+B1/C1,SUM(A1:C3,D6*D12-E12))",
      "depth":0
   },
   {
      "name":"A1+B1/C1",
      "depth":1
   },
   {
      "name":"A1+B1",
      "depth":2
   },
   {
      "name":"A1",
      "depth":3
   },
   {
      "name":"B1",
      "depth":3
   },
   {
      "name":"C1",
      "depth":2
   },
   {
      "name":"SUM(A1:C3,D6*D12-E12)",
      "depth":1
   },
   {
      "name":"A1:C3",
      "depth":2
   },
   {
      "name":"D6*D12-E12",
      "depth":2
   },
   {
      "name":"D6",
      "depth":3
   },
   {
      "name":"D12-E12",
      "depth":3
   },
   {
      "name":"D12",
      "depth":4
   },
   {
      "name":"E12",
      "depth":4
   }
]

Not finding javascript file

Not sure why I am getting a 404 error, path to script index.js seems to be correct as it is in the same folder as the html file. I have tried every path that I can think of, not sure what is wrong here.

enter image description here

enter image description here

enter image description here

I have tried different paths and have tried absolute path as well. Thank you for your help.

Update Server.js:
enter image description here

Replace text when not prefixed by a specific character [duplicate]

How do I create a Regex pattern which allows me to replace target characters when not prefixed by a specific character, e.g. space or underscore

e.g.

replace Street with _Street when prefixed with an underscore in

  • HillStreet -> Hill_Street (replaced to add underscore)
  • Hill_Street -> Hill_Street (no change as it was already prefixed)

I’ve tried this but it still returns HillStreet

let name = "HillStreet"
let tidiedName = name
        .replaceAll("[^_]Street", "_Street");
console.log(tidiedName);

Fetch() calls from Node.js always create new Express sessions

Below is a stripped-down segment of a webshop server with 2 APIs: ./login to login and ./products to show products. The products should only be shown after a succesful login.

I’m using TypeScript with Node.js and Express with session management enabled. The code below also tries to test the server by sending fetch() requests to the APIs. NOTE: So I’m sending fetch() requests from within Node.js, not from a browser. The code below produces the following output:

Login session ID: um2RykooJCer7Oy7YmJQs7s9ge3mZWL1
Products session ID: uAk03ochUM56rzJjPvbiRnFuPG8CUqTB
Products response: Error: Not logged in

It can be seen that the session IDs are different, that’s why it fails to show products. When I leave the code running and type in the API calls manually in a browser:

http://localhost:3000/login
http://localhost:3000/products

Then the code works correctly, with the browser displaying “Login OK” and then “Apple, Orange, Pear” both with the same session ID.

So the question is: How can the server test be made to work correctly with fetch() from Node.js, the same way as it works when called from a browser? Are there some options that can be given to the fetch() requests or to Express? I have not found any yet.

Bonus question: Can it also be made to work with the npm package node-fetch? I use that because the built-in fetch() from Node.js gives errors in other places.

PS I’m using the most recent versions of Node.js (v21.5), Express, express-session and node-fetch.

import Express from "express";
import Session from "express-session";
// Uncomment this to use the node-fetch module, but gives the same result:
// import fetch from "node-fetch";

declare module 'express-session' {
    interface SessionData
    {
        loggedIn: boolean;
    }
}

class App
{
    express = Express();

    start()
    {
        let session = Session( { secret: "my-secret", /* options? */ } );
        this.express.use( session );
        this.express.get( "/login", ( request, response ) => this.onLoginRequest( request, response ) );
        this.express.get( "/products", ( request, response ) => this.onProductsRequest( request, response ) );
        this.express.listen( 3000, () => this.requestLogin() );
    }

    // =================================== Login

    requestLogin()
    {
        fetch( 'http://localhost:3000/login', { /* options? */ } )
            .then( result => this.showProducts() );
    }

    onLoginRequest( request: Express.Request, response: Express.Response )
    {
        console.log( "Login session ID: " + request.session.id );
        request.session.loggedIn = true;
        response.send( "Login OK" );
    }

    // =================================== Products

    showProducts()
    {
        fetch( 'http://localhost:3000/products', { /* options? */ } )
            .then( result => this.onProducts( result ) );
    }

    onProductsRequest( request: Express.Request, response: Express.Response )
    {
        console.log( "Products session ID: " + request.session.id );
        if( !request.session.loggedIn )
            response.send( "Error: Not logged in" );
        else
            response.send( "Apple, Orange, Pear" );
    }

    onProducts( result: any )
    {
        result.text()
            .then( ( text: string ) => console.log( "Products response: " + text ) );
    }
}

( new App() ).start();

problems with cookies with express-session node.js

i deploy my api in fl0 and use the free url from fl0 and deploy my frontend in vercel, the problem is that cookies doesnt save in the client,

my configuration of express-session is:

const store = connectMongo.create({
mongoUrl: process.env.MONGODB_ACCESS_STRING,
ttl: 24 * 60 * 60 * 10000
})

export const sessions = session({

store,

secret: process.env.SECRET_COOKIE_KEY,

resave: false,

saveUninitialized: false,

cookie: {

secure: true ,

httpOnly: true,

domain: 'xxx-xxxx-xxx.vercel.app',

sameSite: 'none',
}
})

this is the app configuration of express-session, cors and passport

const app = express()

app.use(cors({
origin: '``https://xxx-xxxx-xxx.vercel.app``',
credentials: true,
}));

app.use(express.json())

app.use(sessions)

app.use(passportInitialize)

app.use(passportSession)

and the fetch from client:

const res = await fetch(${process.env.NEXT_PUBLIC_BACKEND_URL}/Login`,

{
method: 'POST',

credentials:'include',

headers: {
'Content-Type': 'application/json'
},

body: JSON.stringify({
email: email,
password: password,
})

  })

can somebody helpme? in the localhost everything work but in deploy the cookies fail, everything else work good

i think that i have configuration wrong but i don’t know

Is TanStack Query/ react-query using ReactJs useState under the hood?

I been looking through the code & it seems that TanStack uses observers to notify completion of HTTP requests. I see there a is concept of setState but I have yet to connect the code to a call to ReactJs setState.

In this code below, there is no parents, prop changes or state to cause re-render, yet, when data changes 1 second later, a re-render indeed occurs.

I am trying to understand if it is TanStack Query that has abstracted away ReactJs executions that trigger the re-render or if my functional component has “reacted” to the reference of data changing.

import React from 'react';
import { useQuery } from '@tanstack/react-query';

function asyncFunc() {
  console.log('DBG-asyncFunc');
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('done');
    }, 1000);
  });
}

function onClick() {
  window.location.reload();
}

const Sandbox = () => {
  const { data } = useQuery({
    queryKey: ['whatevs', {}],
    queryFn: async () => {
      const result = await asyncFunc();
      return result;
    },
    ...{ staleTime: 0, cacheTime: 0 },
  });

  console.log('DBG-a-render', data);

  return (
    <div>
      <h4>Async Value: {data}</h4>
      <hr />
      <button type="button" onClick={onClick}>
        Reload
      </button>
    </div>
  );
};

export default Sandbox;

Discord Integration with HTML

Hello,

I am attempting to make a HTML website with Discord Bot Intergration to allow my server staff to have their own platform to manage server aspects from. With this website; I am hoping to achieve that they are able to login via discord (which I have already configured and sorted) which displays a profile page of their discord details (name, id etc.) as well as their rank (Admin, Mod etc.).

Furthermore, I want to make pages that are restricted to discord roles so that per say ‘Server Management’ has access to more pages than ‘Admin’ have. If a member is assigned ‘Server Management’ more dropdown menus are showcased on their dashboard and they are able to access them. I am slightly new to HTML, JS type stuff however am sure I am able to tackle this with the right assistance.

Let me know if there is anything specifically that can point me in the right direction on being able to do this.

Parts I have tried before

I have been able to configure the login side of things but I am unable to find out how to do the other parts.

Many Thanks,
Liam

window.location.href Loads WHOLE URL When INCOMPLETE URL Input is Submitted by Form

When text is entered into this form, it then loads a webpage with that typed text appended at the end of my domain name, to create the full page url. (Incidentally, it also disables the typed Enter key to submit, because I only want the clicked Submit button to submit the form.)

It works, but too well. Weirdly, I can type “ann” and be directed to mysite.com/annex. Worse yet, typing in “an” directs me to mysite.com/anabelle for example … it’s defaulting to whichever existing page is first in alphabetical order (ana comes before ann). How do I limit this behavior, so users must type the ENTIRE word or else go to a 404 error?

<!-- Location Input Form ENTER Button Disabler. Prevents ENTER from submitting form. See also in body form: onkeypress="return noenter()" -->
<script type="text/javascript">
function noenter() {
  return !(window.event && window.event.keyCode == 13); }
</script>

<!-- Location Input Form Script, entered location must match url's "/folder" since it's appended to the domain name. For alts, add a redirect to HTACCESS -->
<script language="javascript" type="text/javascript">
    function noenter() {
       return !(window.event && window.event.keyCode == 13); }
    function buttonClick(){
      var url = document.getElementById("inputURL").value;
      window.location.href = "mysite.com/" + url;
      }
</script>

<!-- Location Input Form -->
<form>
<div class=formfieldcontainer>
<input class="formfield" onkeypress="return noenter()" type="text" id="inputURL" name="inputURL" value="">
</div>
<input class="submitbutton" type="button" value="Submit" onclick="buttonClick()">
</form>

I need users to have to type the ENTIRE word to access a page, not just the first few letters. Any ideas? Thank you!

How do I make a bubble appear above the slider?

I need some help with the code here.
I want the bubble to be displayed above the slider and also move with the slider. The movement works, but it is displayed above the headline (see picture) and not directly above the slider.How the slider looks now
Here is the code:

The CSS code:

    label {
        display: block;
        margin-bottom: 10px;
    }

    .slider-box {
        border-radius: 8px;
        background-color: #272b3a;
        padding: 20px;
        display: inline-block;
        margin-bottom: 20px;
        align-items: center;
        width: 100%; /* Änderung hier */
        position: relative; /* Änderung hier */
    }

    input[type="range"] {
        width: 100%;
        margin-top: 5px;
        border: none;
        outline: none;
        -webkit-appearance: none;
        background-color: #343a40;
        border-radius: 15px;
    }

    input[type="range"]::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #007bff;
        cursor: pointer;
    }

    output {
        display: inline-block;
        margin-left: 10px;
        font-weight: bold;
    }

    button {
        margin-top: 20px;
        margin-right: 10px;
        padding: 10px;
        font-size: 16px;
        cursor: pointer;
    }

    .bubble {
        background-color: #007bff;
        color: #fff;
        border-radius: 5px;
        padding: 5px 10px;
        position: absolute;
        top: -40px;
        left: 50%;
        transform: translateX(-50%);
        white-space: nowrap;
        display: none;
    }

The HTML code:


<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="slider-box">
                <label for="ramSlider">RAM Gr&ouml;&szlig;e:</label>
                <div class="bubble" id="ramBubble">1 GB</div>
                <input type="range" id="ramSlider" min="1" max="32" step="1" value="1" oninput="updateRamValue(); showBubble();" onmousemove="showBubble();" onmouseleave="hideBubble()">
                <output id="ramOutput">1 GB</output>
                <br>
                <button class="btn btn-sm btn-primary" onclick="displayConfigurations()">Konfiguration kaufen</button>
                <button class="btn btn-sm btn-primary" onclick="" style="float: right;">Hilfe</button>
            </div>

There is the JavaScript code:
I think that’s where the problem lies. Unfortunately I’m not very good at Javascript.

                var thumbWidth = 20;

                function updateRamValue() {
                    var ramSlider = document.getElementById("ramSlider");
                    var ramOutput = document.getElementById("ramOutput");
                    ramOutput.textContent = ramSlider.value + " GB";
                }

                function showBubble() {
                    var ramBubble = document.getElementById("ramBubble");
                    var ramSlider = document.getElementById("ramSlider");

                    

Positions the bubble right over the slider


                    var thumbPosition = (ramSlider.value / (ramSlider.max - ramSlider.min)) * (ramSlider.offsetWidth - thumbWidth);
                    var sliderLeft = ramSlider.getBoundingClientRect().left;

                    
                    var bubbleLeft = Math.max(0, Math.min(thumbPosition, ramSlider.offsetWidth - thumbWidth));
                    ramBubble.style.left = sliderLeft + bubbleLeft - thumbWidth / 1 + 'px';

                    ```Shows the bubble

               ramBubble.style.display = 'inline-block';
            }

            function hideBubble() {
                var ramBubble = document.getElementById("ramBubble");
                ramBubble.style.display = 'none';
            }

            function displayConfigurations() {
                var ramSlider = document.getElementById("ramSlider");
                var ramLink = "https://edv-hosting.com/store/minecraft/minecraft-server-05x-cpu?configoption[55]=" + ramSlider.value;
                window.open(ramLink, '_blank');
            }

            ```shows the bubble when loading
                document.addEventListener("DOMContentLoaded", function () {
                    showBubble();
                });

I hope you can help me