How to print JSON data with map in react

That the data in firebase

ref = db.reference('/home1')
ref.set({
'slider':
[ 
  {"id" : "1" ,"name":"first","url":"images/gateaux/2D3A3227.jpg"},
  {"id" : "2" ,"name":"second","url":"images/gateaux/pas/2D3A3470.jpg"},
  {"id" : "3" ,"name":"third","url":"images/anniv/deux/2D3A3497.jpg"},
  {"id" : "4" ,"name":"four","url":"images/anniv/2D3A3106.jpg"},
  {"id" : "5" ,"name":"five","url":"images/anniv/2D3A3365.jpg"},
  {"id" : "6" ,"name":"six","url":"images/gateaux/2D3A5245.jpg"}
]
})

And my code in react, i try to print the data from firebase, when i print just “product” i receive all the data, when i print “product.id” i receive slider and when i prind “product.name” i receive undefined and i want to receive the name like “first” same for url.I need help please

export default function Patiss() {
const [home1, sethome1] = useState([]);
useEffect(()=>{
  const usersRef = ref(database,'home1')
  get(usersRef).then((snapshot) => {
    if(snapshot.exists()){
      const userArray = Object.entries(snapshot.val()).map(([id,data])=>({
         id,
        ...data,
      }));
      sethome1(userArray);
     // console.log(userArray)
    }else{
      console.log('no data available');
    }
}).catch((error)=>{
  console.error(error);
});
},[]);
const navigate = useNavigate()
const Keti = () =>{
  navigate("/")
}
return (
  // <div >
    <div className=" mx-auto max-w-2xl px-4 py-2  ">
      <div className="mt-10 grid grid-cols-1">
      {/* {home1.length > 0 && home1.map((product, index) => { */}
      {home1.map((product, index) => {
          //  console.log(`${product.name}`); // Should now log the name correctly
           console.log(product); 
           console.log(product.id); 
           console.log(product.name); 
              return (
                <div key={index} className="productDisplay"
                  onClick={() => {
                    navigate(`/home1/${product.id}`);
                  }}
                >
            </div>
        );
        })}
      </div>
    </div>
)}

console.log(product) -> all the data print, json
console.log(product.id) -> slider 
console.log(product.name) -> undefined 

Implementing Refresh Token

So I have read some ways to implement a Refresh Token to your website, but I could not understand it as the layout is very different from my School’s project layout. Does anyone know how I could implement for my style of code? It basically follows MVC guidelines with model, routes, controllers.

jwtMiddleware.js:


//////////////////////////////////////////////////////
// REQUIRE DOTENV MODULE
//////////////////////////////////////////////////////
require("dotenv").config();

//////////////////////////////////////////////////////
// REQUIRE JWT MODULE
//////////////////////////////////////////////////////
const jwt = require("jsonwebtoken");

//////////////////////////////////////////////////////
// SET JWT CONFIGURATION
//////////////////////////////////////////////////////
const secretKey = process.env.JWT_SECRET_KEY;
const tokenDuration = process.env.JWT_EXPIRES_IN;
const tokenAlgorithm = process.env.JWT_ALGORITHM;

//////////////////////////////////////////////////////
// MIDDLEWARE FUNCTION FOR GENERATING JWT TOKEN
//////////////////////////////////////////////////////
module.exports.generateToken = (req, res, next) => {
    const payload = {
      userId: res.locals.userId,
      timestamp: new Date()
    };

   
  
    const options = {
      algorithm: tokenAlgorithm,
      expiresIn: tokenDuration,
    };
  
    const callback = (err, token) => {
      if (err) {
        console.error("Error jwt:", err);
        res.status(500).json(err);
      } else {
        res.locals.token = token;
        next();
      }
    };
  
    const token = jwt.sign(payload, secretKey, options, callback);
  };

//////////////////////////////////////////////////////
// MIDDLEWARE FUNCTION FOR SENDING JWT TOKEN
//////////////////////////////////////////////////////
module.exports.sendToken = (req, res, next) => {
    res.status(200).json({
      message: res.locals.message,
      token: res.locals.token,
    });
  };

//////////////////////////////////////////////////////
// MIDDLEWARE FUNCTION FOR VERIFYING JWT TOKEN
//////////////////////////////////////////////////////
module.exports.verifyToken = (req, res, next) => {
    const authHeader = req.headers.authorization;
  console.log("hi")
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ error: 'No token provided' });
    }
  
    const token = authHeader.substring(7);
  
    if (!token) {
      return res.status(401).json({ error: "No token provided" });
    }
  
    const callback = (err, decoded) => {
      if (err) {
        return res.status(401).json({ error: "Invalid token" });
      }
  console.log(decoded.userId)
      res.locals.userId = decoded.userId;
      res.locals.tokenTimestamp = decoded.timestamp;
      
  
      next();
    };
  
    jwt.verify(token, secretKey, callback);
  };

.env:

JWT_EXPIRES_IN=50m
JWT_ALGORITHM=HS256
REFRESH_TOKEN_EXPIRES_IN=7d

mainRoutes.js:



router.post("/login", userController.login, bcryptMiddleware.comparePassword, jwtMiddleware.generateToken, jwtMiddleware.sendToken);

router.post("/register", userController.checkUsernameOrEmailExist, bcryptMiddleware.hashPassword, userController.register, userController.login, jwtMiddleware.generateToken, jwtMiddleware.sendToken);

I tried setting the token refresh to expire after 7 days. And then make the access token last for 1 min. Added another controller where after however long the access token lasts, so then when it expires, It will instead use the Refresh Token Instead. But that is probably the wrong way of doing it as I do not understand how to really implement it

Simple flashing image animation using a javascript

I am a beginner in a Javascript programming.
And I need some help regarding to image animation.

I would like to achieve following results :

  • Icon have to be flashing in red color with out any click event.
    (like showing when there is an error, notifing to users.)
  • Stop button to make it stop the animation / transition.
  • One image file should be used in order to achieve the point stated above.
  • Icon should be flashing without the click event.
  • We may use a javascript in order to implement the animation, but it have to be work even when the internet is not available.

I found a sample on the internet, try to do myself, and here is the code that I’ve worked on :

HTML

<div class="split">
  <img src="https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FtKZbq%2FbtsEb7zLet0%2FHDOJKKBGmhp3kWrFZXXTFk%2Fimg.png" >
</div>

CSS

*, *:before, *:after {
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
- background: #000;
}

.split {
  width: 48px;
  height: 42px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  perspective: 400px;
  cursor: pointer;
  background-color: #ff0000;

  &:before {
    color: #777;
    letter-spacing: 1px;
    font-size: 10px;
    position: absolute;
    bottom: -30px;
    left: 50%;
    transform: translate(-50%);
  }

  img {
    height: 100%;
    width: 100%;
    opacity: 0;
  }

  div {
    position: absolute;
    z-index: 1;
    background-repeat: no-repeat;
    transform: rotateY(-50deg) scale(0.5);
    opacity: 0;
    transform-origin: bottom;
    transition: all .6s cubic-bezier(.71, .05, .09, .91);
  }

  &.active {
    div {
      opacity: 1;
      transform: rotate(0deg) translateY(0);
    }
  }
}

Javascript

var Split = function() {
  this.$t = $(".split");
  this.gridX = 48;
  this.gridY = 46;
  this.w = this.$t.width();
  this.h = this.$t.height();
  this.img = $("img", this.$t).attr("src");
  this.delay = 0.05;


  this.create = function() {
    $("div", this.$t).remove();

    for (x = 0; x < this.gridX; x++) {
      for (y = 0; y < this.gridY; y++) {
        var width = this.w / this.gridX * 101 / this.w + "%",
            height = this.h / this.gridY * 101 / this.h + "%",
            top = this.h / this.gridY * y * 100 / this.h + "%",
            left = this.w / this.gridX * x * 100 / this.w + "%",
            bgPosX = -(this.w / this.gridX * x) + "px",
            bgPosY = -(this.h / this.gridY * y) + "px";

        $("<div />")
          .css({
          top: top,
          left: left,
          width: width,
          height: height,
          backgroundImage: "url(" + this.img + ")",
          backgroundPosition: bgPosX + " " + bgPosY,
          backgroundSize: this.w + "px",
          transitionDelay: x * this.delay + y * this.delay + "s"
        })
          .appendTo(this.$t);
      }
    }
  };

  this.create();

  this.$t
    .on("click", function() {
    $(this).toggleClass("active");
  })
    .click();
};

window.onload = function() {
  var split = new Split();
  var gui = (function datgui() {
    var gui = new dat.GUI();
    gui.add(split, "gridX", 1, 20).step(1).onChange(function(newValue) {
      split.create();
    });
    gui.add(split, "gridY", 1, 20).step(1).onChange(function(newValue) {
      split.create();
    });
    gui.add(split, "delay", 0, 0.3).step(0.01).onChange(function(newValue) {
      split.create();
    });
    return gui;
  })();
};

when click on the image, its changing colour to red (flashing).
but its still look like awkward.

So, I would like to ask you a question to do you have a better idea to achieve those points stated above? If so, could you please let me know how to improve the result?

also, on the sample, there was a click event in order to make it transition / animation.

I would like to make it repeat faster (maybe using a loop to look like flashing and make it look like more decent.

https://codepen.io/cpadhwfr-the-decoder/pen/QWoQmEJ

Thank you in advance, I will highly appreciated, if you can help me to understand the concept of javascript transition / animation.

How to run reactNativeFragment inside existing application

I’m trying to integrate react native into existing Android application. Most of the code, js will be running ‘headless'(no ui, only logic), and communicate with android UI.
Now I’m at a point when I want to open small JS fragment inside the android application, purely for debug tools. I followed the official documentation of how to migrate react native into existing app, but my issue is that attempting to open reactNativeFragment results in opening another JS thread(can see another thread in chrome tools).

This is the place where I start my react native process (it only loads js, not the UI).

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReactRootView = new ReactRootView(this);
        List<ReactPackage> packages = new PackageList(getApplication()).getPackages();
        packages.add(new MyAppPackage());
        
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackages(packages)
                .setDefaultHardwareBackBtnHandler(this)
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "hermesdm2", null);

And here, I have a button that should open JS UI window that I can use for debug purposes(easier to debug from js):

        mButton = findViewById(R.id.button);
        View frameLayout = findViewById(R.id.reactNativeFragment);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Fragment reactNativeFragment = new ReactFragment.Builder()
                        .setComponentName("hermesdm2")
                        .setFabricEnabled(false)
                        .build();
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.reactNativeFragment, reactNativeFragment)
                        .commit();
                frameLayout.setVisibility(View.VISIBLE);
            }
        });

But, as I said, this opens another JS process instead of reusing existing one, which I dont want to. How would I do that?

I tried to play around with component names, I tried to run the existing reactRootView inside the fragment too(that actually should be possible but I didnt success so far.

How do I parse a text response to only bring back the token after “Access”

I’m trying to do a pre-request script to retrieve a bearer auth token. I’ve gotten it to work but need to create a auth token constant from the response. The response comes back with two tokens, a refresh and access token. I would to retrieve the access token and assign it as a variable so that I can proceed to use it in my api calls.
Postman Code

This is the response:
“refresh”:”fjdasklfjsakldfjaslkfjlkasdf”,”access”:”dsfjalskfjaslkdfjaklsdfjafdslfkja”

This is my first API project so any advice would be great! I’ve read about Access and Response tokens. Not sure how to incorporate both (or if I should). So far for testing i’ve been using the access token to try test API calls.

I’ve tried to parse the token by doing a startswith(“access:”).

Such as this:
`authHeader.startsWith(“access”)){ token = authHeader.substring(9, authHeader.length);

JSDoc to describe a React useState?

How do you describe a React state using JSDoc?

In other words, how do you simplify this into a one-liner?

/** The animal you're with */
let animal;
let setAnimal;
[animal, setAnimal] = useState()

In yet other words…

/** what do you put here to describe `animal`? */
const [animal, setAnimal] = useState()

AppsScript formula error for string type conversion

I’m trying to do a simple function in AppsScript (is using Javascript) to convert a given date time string which is in a custom date format. I keep getting increasingly weird errors with types. Can someone shed some light on what is going on with the following function.

When I run this I get “Exception: Invalid argument: undefined”
If I pass the dateTimeString directly to the parseDate function, I get error “Exception: Invalid argument: date. Should be of type: String” 

/**
 * Converts a string to a date-time value
 *
 * @param dateTimeString
 * @customfunction
 */
function stringToDateTime(dateTimeString) {
  var stringDateTime = new String(dateTimeString)
  var format = Utilities.parseDate(stringDateTime, "GMT", "yyyy-MM-dd'T'HH:mm:ssX")
  return format  
}

var x = stringToDateTime("2023-06-30T18:28:01+10:00")
Logger.log(x)

Thank you

How to Rewrite the Url for a Nuxt 3 Dynamic Route

In next.js given the following folder structure, a mobile or desktop page can be loaded based on the user agent.

/middleware.ts
/pages
  /_viewport
    /mobile.tsx
    /desktop.tsx

In next.js there is a built in helper userAgent which can detect this. In this middleware function, the user agent is detected and the response is re-written.

import { userAgent } from 'next/server'

export function middleware(request) {
  const { device } = userAgent(request)
  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
  url.searchParams.set('viewport', viewport)
  return NextResponse.rewrite(url)
}

How can I do the same thing with Nuxt 3? I need completely different structures for the product page, mobile vs desktop, and it would be way cleaner if I could just have two different pages. The product pages of course need to be dynamic.

I have the following folder structure:

/pages
  /_viewport
    /desktop
      /products
        /[handle].vue
    /mobile
      /products
        /[handle].vue

I want to load a certain product page for mobile or desktop in Nuxt 3. I am having a very hard time getting this to work and for the sake of simplicity, let’s say that we have a similar helper, userAgent in Nuxt 3. How can we load a certain product page based on if the user agent is mobile or desktop and rewrite the url?

I want to have a middleware function setup that does something like this in server/middleware/index.js

Assuming we have our own userAgent util working, if a user visits the mobile product page /_viewport/mobile/products/t-shirt.vue, how can we re-write the url so that /products/t-shirt is shown in the browser, even though we are on the mobile version of the product page?

I would appreciate any help with this, I have been struggling with this for way too long and would also appreciate if anyone had a better approach to setting up the pages structure. Note that I know I can use media queries, but the page just gets way too messy.

Next.js 14 Server Actions: Issue Modifying Cookies

I’m currently developing a Next.js 14 application and have encountered an issue with modifying cookies. Despite following the Next.js documentation on server actions and cookie manipulation, I’m receiving an error when trying to set cookies during the signout process.
The error message states: “Cookies can only be modified in a Server Action or Route Handler.

Here’s the relevant code snippet from my project:

// pwa/src/utils/globalActions.ts

'use server';

import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';

export const signout = async () => {
  cookies.set('token', '', { maxAge: -1 });
  cookies.set('refreshToken', '', { maxAge: -1 });
  cookies.set('user', '', { maxAge: -1 });
  return redirect('/auth/signin');
};
// pwa/src/utils/apiAxios.ts (This file is used by both client and server components)

import axios, {
    type AxiosResponse,
    type AxiosError,
    type AxiosInstance,
} from 'axios';
import { signout } from './globalActions';

const Axios = axios.create({
    baseURL: ENTRYPOINT,
    headers: {
        Accept: 'application/ld+json',
        'Content-Type': 'application/ld+json',
    },
});

Axios.interceptors.response.use(
    response => response,
    async (error: AxiosError<ApiResponseError>) => {
        if (error.status === 401 || error.response?.status === 401) {
            await signout();
        }

        return Promise.reject(error);
    },
);

I’ve checked my usage against the Next.js documentation and made sure to use the server execution context (‘use server’;). Yet, the issue persists. I suspect I might be missing a detail in how Next.js 14 handles cookies in server actions or there might be a specific configuration step I’ve overlooked.

Has anyone encountered this issue before, or does anyone have insights on how to properly modify cookies within server components in Next.js 14?
Any help or pointers would be greatly appreciated.

React Native setup failed with macOS m2 chip

I’ve encountered challenges while attempting to set up a React Native project on my new MacBook over the past two days. Navigating through the macOS environment and React Native (RN), I’ve faced difficulties building the project and observing it in action. It’s essential to note that I’m a newcomer to both macOS and RN, and I’ve opted not to use ExpoGo due to specific requirements. Let me detail the issues in my process:

  1. Node.js Installation:
    I initiated the process by installing Node.js from the official website.

  2. React Native Project Initialization:
    Using the command npx react-native init AwesomeProject worked smoothly. However, during the Installing dependencies phase, an issue arose (screenshot). Although it’s stated that this won’t affect the initialization, I had to navigate to /ios, execute bundle install (requiring sudo due to failures), and then run bundle exec pod install (also requiring sudo with --allow-root).

  3. Build and Run Error:
    Despite successful installations, attempting to build and run the project resulted in an error (screenshot).

Environment Details:

  • macOS: Sonoma M2 chip
  • Ruby: 2.6.10 (System default)
  • Node: 20 (Current LTS)
  • Xcode: 15.2
  • Homebrew: 4.2.3
  • Gem: 3.0.3.1

Any insights or suggestions would be greatly appreciated. Thank you!

This issue persisted even after various attempts, including installing CocoaPods via Homebrew and sudo gem install ffi, found this in some forums.

I tried reinstalling and purging various components (Node, Homebrew, Ruby) multiple times, including updating Ruby to version 3. Despite these efforts, I remain stuck with the same issues.

How to modify code to calculate lag and autocorrelation (GEE)?

My problem that I tried to modify the code in below that used Landsat as input to use MODIS NDVI (MOD13Q1) product as input.
I’m not familiar with coding by using GEE, for that I want a to calculate autocorrelation between NDVI and any other online precipitation monthly data.
thank you in advance.

// Precipitation (covariate)
var chirps = ee.ImageCollection('UCSB-CHG/CHIRPS/PENTAD');

// Join the t-l (l=1 pentad) precipitation images to the Landsat.
var lag1PrecipNDVI = lag(landsat8sr, chirps, 5);

// Add the precipitation images as bands.
var merged1PrecipNDVI = ee.ImageCollection(lag1PrecipNDVI.map(merge));

// Compute and display cross-covariance.
var cov1PrecipNDVI = covariance(merged1PrecipNDVI, 'NDVI',
    'precipitation').clip(roi);
Map.addLayer(cov1PrecipNDVI.arrayGet([0, 1]), {},
    'NDVI - PRECIP cov (lag = 5)');

// Compute and display cross-correlation.
var corr1PrecipNDVI = correlation(cov1PrecipNDVI).clip(roi);
Map.addLayer(corr1PrecipNDVI, {
    min: -0.5,
    max: 0.5
}, 'NDVI - PRECIP corr (lag = 5)');

// Join the precipitation images from the previous month.
var lag30PrecipNDVI = lag(landsat8sr, chirps, 30);

var sum30PrecipNDVI = ee.ImageCollection(lag30PrecipNDVI.map(function(
    image) {
    var laggedImages = ee.ImageCollection.fromImages(image
        .get('images'));
    return ee.Image(image).addBands(laggedImages.sum()
        .rename('sum'));
}));
 
// Compute covariance.
var cov30PrecipNDVI = covariance(sum30PrecipNDVI, 'NDVI', 'sum').clip(
    roi);
Map.addLayer(cov1PrecipNDVI.arrayGet([0, 1]), {},
    'NDVI - sum cov (lag = 30)');

// Correlation.
var corr30PrecipNDVI = correlation(cov30PrecipNDVI).clip(roi);
Map.addLayer(corr30PrecipNDVI, {
    min: -0.5,
    max: 0.5
}, 'NDVI - sum corr (lag = 30)');

CORS issue while attempting to make a POST request from my React [duplicate]

I am facing a CORS issue while attempting to make a POST request from my React frontend to a PHP backend. The error message in the browser console is as follows:

Access to fetch at 'http://localhost/mcha-express/website/api/v1/book/:csrfToken' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

book.js:33 
        
POST http://localhost/mcha-express/website/api/v1/book/:csrfToken net::ERR_FAILED

book.js:62 Error submitting the form: TypeError: Failed to fetch
    at handleSubmit (book.js:33:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (react-dom.development.js:9097:1)
    at react-dom.development.js:9288:1

Here are the relevant parts of my frontend and backend code:

// Frontend (book.js):

import React, { useState, useEffect } from 'react';
import Navbar from './navbar';
import Footer from './footer';

function Book(){
  useEffect(() => {
    document.title = '';
  }, []);

  const [data, setData] = useState({
    full_name: '',
    email_address: '',
    contact_number: '',
    complete_address: '',
    details: ''
  });

  const [submitting, setSubmitting] = useState(false);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setData((prevData) => ({
      ...prevData,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const response = await fetch('http://localhost/mcha-express/website/api/v1/book/:csrfToken', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          csrfToken: 'a73f54b65f76467e9413a5c5fde2e32d1f3b4b82c7c0b0634a12bd6ca0b87dc2', 
          ...data,
        }),
      });

      const result = await response.json();

      // Handle the response accordingly
      if (response.ok) {
        console.log(result.message); // Successful response
        // Reset the form after successful submission if needed
        setData({
          full_name: '',
          email_address: '',
          contact_number: '',
          complete_address: '',
          details: '',
        });
      } else {
        console.error(result.error); // Error response
        // Handle error, display message, etc.
      }
    } catch (error) {
      console.error('Error submitting the form:', error);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      <Navbar/>
      {/* Book Section Start */}
      <section className='book'>
        <div className='book-bg'></div>
        <div className='container'>
          <form onSubmit={handleSubmit}>
            <h1>BOOK</h1>
            <p>Book now for effortless parcel delivery with us! Simply fill out the form, secure your slot, and leave the rest to us.</p>
            <div className='form-labels'>
              <div className={'response-message error'}>
                <span>Submitting</span>
              </div>
              <div className='labels'>
                <input
                  type='text'
                  placeholder='Full Name'
                  name='full_name'
                  value={data.full_name}
                  onChange={handleInputChange}
                />
                <input
                  type='email'
                  placeholder='Email Address'
                  name='email_address'
                  value={data.email_address}
                  onChange={handleInputChange}
                />
              </div>
              <div className='labels'>
                <input
                  type='number'
                  placeholder='Contact Number'
                  name='contact_number'
                  value={data.contact_number}
                  onChange={handleInputChange}
                />
                <input
                  type='text'
                  placeholder='Complete Address'
                  name='complete_address'
                  value={data.complete_address}
                  onChange={handleInputChange}
                />
              </div>
              <div className='label'>
                <textarea
                  rows='5'
                  placeholder='Please provide the details of your requirements...'
                  name='details'
                  value={data.details}
                  onChange={handleInputChange}
                ></textarea>
              </div>
              <div className='label'>
                <button type='submit'>
                  <span>Submit</span>
                </button>
              </div>
            </div>
          </form>
        </div>
      </section>
      {/* Book Section End */}

      {/* Footer Section Start */}
      <Footer/>
      {/* Footer Section End */}
    </>
  );
}

export default Book;

Backend (index.php):

<?php

$request_uri = $_SERVER['REQUEST_URI'];
$uri_parts = explode('/', $request_uri);
$endpoint = implode('/', array_slice($uri_parts, 2));

include 'api.php';

// POST book
if (strpos($endpoint, 'website/api/v1/book') !== false) {
  header('Content-Type: application/json');
  $csrfToken = end($uri_parts);
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    post_book($csrfToken);
  } else {
    http_response_code(405);
    echo json_encode(['error' => 'Invalid request method for this endpoint']);
  }
} 
?>

Backend (api.php):

<?php
// Security Headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, *");

include 'config.php';
session_start();

// Ito yung magkicreate ng csrf token
function generateCsrfToken() {
  if (!isset($_SESSION['csrf_token']) || !isset($_SESSION['csrf_token_expire']) || $_SESSION['csrf_token_expire'] < time()) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    $_SESSION['csrf_token_expire'] = time() + 300;
  }
  echo json_encode([
    'csrfToken' => $_SESSION['csrf_token'],
    'expiryDate' => $_SESSION['csrf_token_expire'],
  ]);
}

// Ito yung magbavalidate ng token
function validateCsrfToken($sentToken) {
  return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $sentToken);
}

// Ichicheck kung yung csrf token ba is existing
function checkCsrfToken($sentCsrfToken) {
  if (!$sentCsrfToken || !validateCsrfToken($sentCsrfToken)) {
      http_response_code(403);
      echo json_encode(['error' => 'CSRF Token Validation Failed']);
      exit;
  }
}

// POST method ng pag iinsert ng book
function post_book($csrfToken) {
  global $pdo;

  // Defined variable
  $booking_id = 'BI-' . mt_rand(1000000000, 9999999999);
  $full_name = filter_input(INPUT_POST, 'full_name', FILTER_SANITIZE_STRING);
  $email_address = filter_input(INPUT_POST, 'email_address', FILTER_SANITIZE_EMAIL);
  $contact_number = filter_input(INPUT_POST, 'contact_number', FILTER_SANITIZE_STRING);
  $complete_address = filter_input(INPUT_POST, 'complete_address', FILTER_SANITIZE_STRING);
  $details = filter_input(INPUT_POST, 'details', FILTER_SANITIZE_STRING);

  // Ichicheck kung invalid ba yung csrf token
  if ($csrfToken !== $_SESSION['csrf_token']) {
      http_response_code(403);
      echo json_encode(['error' => 'CSRF Token Validation Failed']);
      exit;
  }

  // Kapag merong isang field yung missing
  if (!$csrfToken || !$full_name || !$email_address || !$contact_number || !$complete_address || !$details) {
      http_response_code(400);
      echo json_encode(['error' => 'Invalid input data']);
      exit;
  }

  // Taga check kung yung booking_id is nageexist naba
  $existingBookingQuery = $pdo->prepare("SELECT COUNT(*) FROM book WHERE booking_id = ?");
  $existingBookingQuery->execute([$booking_id]);
  $existingBookingCount = $existingBookingQuery->fetchColumn();

  if ($existingBookingCount > 0) {
      http_response_code(400);
      echo json_encode(['error' => 'Booking ID already exists']);
      exit;
  }

  $sql = "INSERT INTO book (booking_id, full_name, email_address, contact_number, complete_address, details) 
          VALUES (?, ?, ?, ?, ?, ?)";

  $stmt = $pdo->prepare($sql);
  $stmt->bindParam(1, $booking_id);
  $stmt->bindParam(2, $full_name);
  $stmt->bindParam(3, $email_address);
  $stmt->bindParam(4, $contact_number);
  $stmt->bindParam(5, $complete_address);
  $stmt->bindParam(6, $details);

  if ($stmt->execute()) {
      echo json_encode(['message' => 'Booking successfully submitted!']);
  } else {
      echo json_encode(['error' => '[Error] Failed to submit your booking.']);
  }

  $stmt->closeCursor();
}
?>

Question Details:

  • I have already set the necessary CORS headers in my PHP backend.
  • The error specifically mentions an issue with the preflight OPTIONS request not having an HTTP ok status.

What I’ve Tried:

  • I have checked and confirmed that my CORS headers are correctly set.
  • I have reviewed similar questions on Stack Overflow, but none of the solutions seem to resolve my issue.

Request for Assistance:

I would appreciate any insights or suggestions on how to resolve this CORS issue. Is there something I might be missing in my setup? Any help would be greatly appreciated!

Error executing a test with jest in React with Vite project

I have a problem when i try to execute the test in my project, i spend a while searching how can i fix it but i don’t find an answer.

The command that i using for execute the test is:

package.json

"test": "jest --watchAll --detectOpenHandles"

and what i see in the console is the next error:

  ● Test suite failed to run                                      
                                                                  
    Jest encountered an unexpected token                          
                                                                  
    Jest failed to parse a file. This happens e.g. when your code 
or its dependencies use non-standard JavaScript syntax, or when Je
st is not configured to support such syntax.                      
                                                                  
    Out of the box Jest supports Babel, which will be used to tran
sform your files into valid JS based on your Babel configuration. 
                                                                  
    By default "node_modules" folder is ignored by transformers.  
                                                                  
    Here's what you can do:                                       
     • If you are trying to use ECMAScript Modules, see https://je
stjs.io/docs/ecmascript-modules for how to enable it.             
     • If you are trying to use TypeScript, see https://jestjs.io/
docs/getting-started#using-typescript                             
     • To have some of your "node_modules" files transformed, you 
can specify a custom "transformIgnorePatterns" in your config.    
     • If you need a custom transformation specify a "transform" o
ption in your config.                                             
     • If you simply want to mock your non-JS modules (e.g. binary
 assets) you can stub them out with the "moduleNameMapper" config 
option.                                                           
                                                                  
    You'll find more details and examples of these config options 
in the docs:                                                      
    https://jestjs.io/docs/configuration                          
    For information about custom transformations, see:            
    https://jestjs.io/docs/code-transformation                    
                                                                  
    Details:                                                      
                                                                  
    <root>node_modules.
[email protected]_modulesquery-stringindex.js:1      
    ({"Object.<anonymous>":function(module,exports,require,__dirna
me,__filename,jest){import * as queryString from './base.js';     
                    ^^^^^^                                        
                                                                  
    SyntaxError: Cannot use import statement outside a module     
                                                                  
      2 | import { HeroCard } from '../components';               
      3 |         
    > 4 | import queryString from 'query-string';                 
        | ^                                                       
      5 | import { getHeroesByName } from '../helpers';           
      6 |                                                         
      7 | export const SearchPage = () => {                       
                                                                  
      at Runtime.createScriptFromCode (node_modules/.pnpm/jest-run
[email protected]/node_modules/jest-runtime/build/index.js:1505:14)     
      at Object.require (src/heroes/pages/SearchPage.jsx:4:1)     
      at Object.require (src/heroes/pages/index.js:4:1)           
      at Object.require (src/heroes/index.js:1:1)                 
      at Object.require (src/router/AppRouter.jsx:4:1)            
      at Object.require (tests/router/AppRouter.test.jsx:4:1)     

Finally, if i comment the line:

import queryString from 'query-string';

My test pass successfully but i need this importation.

In the console says that i can fix it, searching in the jestjs web for can configure it well, but i don’t understand to much, can anyone help me?

Uncaught ReferenceError: student is not defined at HTMLButtonElement.

the problem is i want the result like this

enter image description here

but it does not show it

what i want is to make a program that show names on webpage as i add them through the input box using array

it’s a very easy program but i don’t whay do i get this error

This is the code :

var students = [];

document
  .getElementById("add-student-btn")
  .addEventListener("click", function() {
    var SNNA1me = document.getElementById("student-input").value;
    student.push(SNNA1me);
    document.getElementById("students").innerHTML = students;
  });
<div style="text-align: center; margin-top: 100px">
  <input type="text" id="student-input" />
  <button id="add-student-btn">Submit</button>
  <div id="students" style="font-size: 30px"></div>
</div>