Next.js (v13) | rewrite and redirect does not work in the Middleware. -> when reques from page (run) but from api (not work)

I am coding with Next.js v13.

You can find the codes I wrote by looking towards the end of this text.

working principle:
1- I’m throwing requests and values to the service that makes a fetch with a client side component.

2- The service receives the incoming request and sends it to the API.

3- the request goes through a “middleware.js” before going to the api

3.1 – reaching api if middleware allows request

3.2 – If the middleware does not allow the request, it performs the necessary actions and redirects to a different page with NextResponse.redirect(…).

my problem:
I trigger my middleware when I go to a normal page and this NextResponse.redirect(…) operation works fine.
HOWEVER!
Unfortunately, when I send a request to an api, it doesn’t work.

Fetch operation in api requests returns data as res.json().

and I’m returning a redirect from the middleware with NextResponse.redirect(…) only.

I think the question is related to this, but I would appreciate it if you could examine it and let me know.

please fallow the steps.
page.js > service(postAPI) > middleware > API

page.js (runing when onSubmit)

await postAPI("/auth/sendVerifyEmail", values).then((data) => {
          if(!data){
            toast.error("Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz.");
            setIsloading(false);
            return;
          }
          else{
            if (data.status === "success") {
              setIsAccessing(true);
              setIsloading(false);
              toast.success(data.message + " Lütfen Bekleyin, yönlendiriliyorsunuz...");
            
              //Bilgi verir ve 5 saniye sonra login sayfasına yönlendirir.
              const timeOut = setInterval(() => {
                if(data.role){
                  setIsloading(false);
                  router.push(`/auth/login/${data.role.toLowerCase()}`);
                }
                else{
                  setIsloading(false);
                  router.push(`/`);
                }
                
                
                clearInterval(timeOut);
              }, 4000);
              
            } else {
              toast.error(data.message);
              setIsloading(false);
            }
          }
        });

service(postAPI) running when onsubmit from page.js

export async function postAPI(URL, body = "", method="POST", headers = {'Content-Type': 'application/json'}){
try {
    const data = await fetch (`${process.env.NEXT_PUBLIC_API_URL + URL}`,{
        method: method,
        headers: headers,
        body: JSON.stringify(body)
        
    }).then(res => res.json())
    .catch(err => console.log(err))
    
    return data;

} catch (error) {
    throw new Error(`API request failed: ${error.message}`);
}        

}

middleware.js (running middleware when service post to api)

  export async function middleware(req, res, next) {
  
  const { pathname } = new URL(req.url) || new URL(req.nextUrl);
  console.log("pathname : " + pathname)
  console.log(data);
  if (
    // istek gidecek sayfaları burada belirledik. eğer bu sayfalara istek giderse kontrol edilecek
    (pathname.startsWith('/api/auth/verifyEmail')) && (req.method === "POST")
  ) {
        //triggered on api request but not working!
        //triggers and works for the page!
        return NextResponse.rewrite(targetUrl);

        }
    else{
        // kullanıcı limiti aşmadı ise isteği gönderir.
        return NextResponse.next();
    }
  }
}

API
API ONLY : OPERATES WITH VALUES SENT TO API AND RETURNS OBJECTS BACK

like this: return res.status(401).json({status: "error", error: error?.message, message: error?.message});

In these structures, I cannot use rewrite or redirect structures in api requests.

there is only one error i got back room:
“SyntaxError: Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON”

I think it’s because I returned it as res.json in the service section but when I deleted it my problem still wasn’t resolved…

Strange behaviour of JS regex

I need to construct a regex that will match patterns like H10, but do not match patterns like H10=123 (note: instead of H there may be [A-z], instead of 10 – [0-9]+)

This one works perfectly on regex101.com: [A-Z]d+[^= ](?!=)

G9=51  // false
H10=10 // false
H10    // true
G0     // true
G0=0   // false

But in JS I have the following problem:

'G10'.match(/[A-Z]d+[^= ](?!=)/g) // ['G10']
'G1'.match(/[A-Z]d+[^= ](?!=)/g) // null

The problem is that in JS for a strange reason this regex does not catch patterns with only single number, like G1. Why this can happen if it is a valid regex according to regex101.com?

find all subsets of a set in JavaScript (how is bitwise operation used here?)

This is based on a previous SO post. Here I don’t understand how the** if(i & Math.pow(2, j)** part is used to select the array element. The code is pasted below.

var arr = [1, 2, 3];

function generatePowerSet(array) {
  var result = [];
  result.push([]);

  for (var i = 1; i < Math.pow(2, array.length); i++, result.push(subset))
    for (var j = 0, subset = []; j < array.length; j++)
      if (i & Math.pow(2, j))
        subset.push(array[j]);

  return result;
}

console.log(generatePowerSet(arr));

I read the answers and Mathematically I get it is using & operator and checking if it is 0 or 1, but I don’t understand the logic behind it. Please can someone explain it?

how can convert word to uppercase in this function

I want to declare a function that get a string and convert the first letter of every word to uppercase.

I wrote this code and it didn’t work correctly .

function titleCase(str) {
    let newStr = str.split(" ");
    for (let i = 0; i < newStr.length; i++) {
        newStr[i][0].toUpperCase()
    }
    return newStr.join(" ");

}

I think about another way but I didn’t find .
can anyone help me?

How would I make my clear cart button work?

So I got my cart page functioning pretty well and I want to know how to make my Clear Cart button remove every item from the cart if possible.

Here’s my code:

``<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
    <script src="https://kit.fontawesome.com/ec308a8989.js" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

    <title>Cart</title>
    <link rel = "stylesheet" href="assets/css/styleCart.css">
</head>
<body>
    <img style="float: left;" src="assets/img/mine.png" width="200" height="80" onclick="Home()">
    <nav class="navbar navbar-expand-sm navbar-dark bg-dark">
        <div class="container-fluid">
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mynavbar">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="mynavbar">
            <ul class="navbar-nav me-auto">
              <li class="nav-item">
                <a class="navborder" href="Tacos.html">Tacos</a>
              </li>
              <li class="nav-item">
                <a class="navborder" href="Burritos.html">Burritos</a>
              </li>
              
              <li class="nav-item">
                <a class="navborder" href="drinks.html">Drinks</a>
              </li>
              <li class="nav-item">
                <a class="navborder" href="desert.html">Deserts</a>
              </li>
              <li>
                <a class="navborder" href="SpecialMenu.html">Special Menu</a>
              </li>
              <li>
                <a class="navborder" href="Cart.html">Checkout</a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    <br>
    <p1>NOW AVAILABLE ON UBER-EATS! </p1>
    <h1>CART</h1>
    <form>
        <div class="card">                        
            <a name="cartSection"></a>
            <div class="cart-row">
                <div class="cart-item-name cart-header cart-column">Item</div>
                <div class="cart-price-header cart-header cart-column">Price</div>
                <div class="cart-quantity cart-header cart-column">Quantity</div>
                <div class="cart-quantity cart-header cart-column">Sub-total</div>
            </div>
            <div class="cart-items">
                <ul id="show-cart">
                    <span-cart>Your cart is empty!</span-cart>
                </ul>
            </div>
        
            <div class="cart-total">Total Cart:$<span id="total-cart"></span></div><br><br>
            <button id="clear-cart">Clear Cart</button><br><br><br>    
            <button type="button" value="Check Out" id="checkOut" onclick="purchase()">Check Out</button>
                           
        </div>
    </form>
    <script src="js/ItemScripts.js"></script>
    <script src="js/drinks.js"></script>
    <script src="js/scriptsCart.js"></script>
    <script src="js/scriptsBurrito.js"></script>
    <script src="js/desert.js"></script>
    <script src="js/scriptsMisc.js"></script>
</body>
</html>`
`var cart = [];

function Item(name, price, count) {
    this.name = name
    this.price = price
    this.count = count
};


var addToCartButtons = document.getElementsByClassName('add-to-cart');
for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i];
        button.addEventListener('click', addToCartClicked);
}

function addToCartClicked(name,price) {
    if(cart === null) {
        cart = [];  
    } 
    var parent1 = document.querySelectorAll('#itemName');
    var name = parent1[0].textContent;
    console.log("1st child of parent1");
    console.log(name)
    var parent2 = document.querySelectorAll('#itemPrice');
    var price = Number(parent2[0].textContent);
    console.log("1st child of parent2");
    console.log(price);

    const Item={
        name: name,
        price: price,
        count: 1,
    
    };
    console.log(Item);

    addItemToCart(name, price, 1);
    
    displayCart();
}



function addItemToCart(name, price, count) {
    for (var i in cart) { 
        if (cart[i].name === name && cart[i].price === price) {
            cart[i].count += count;

            saveCart();
            return; 
        }
    
    }
    var item = new Item(name, price, count);
    cart.push(item);
    saveCart();
}
console.log("add to cart");
console.log(cart);



function listCart() {
    var cartCopy = []; 
    for (var i in cart) {
        var item = cart[i];
        var itemCopy = {};
        for (var p in item) {
            itemCopy[p] = item[p];
        }
        itemCopy.total = (item.price * item.count).toFixed(2);
        cartCopy.push(itemCopy);
    }
    return cartCopy;
};

function displayCart() {
    var cartArray = listCart();
    var output = "";

    for (var i in cartArray) { 
        output += "<div class='itemDetail'>"
            +"<div class='cart-item cart-column'>"
            +cartArray[i].name 
            + "</div>"
            +"<div class='cart-price cart-column'>"
            +" $ "+cartArray[i].price
            +"</div>"
            +" <input class='item-count cart-column' type='number' data-name='"
            +cartArray[i].name
            +"' value='"+cartArray[i].count+"'>"
            +"<div class='subTotal cart-column'>"
            +"  $ "+cartArray[i].total
            +"</div>"
            +"</div>";
    }
    $("#show-cart").html(output);
    $("#count-cart").html(countCart());
    $("#total-cart").html(totalCart());

}


function setCountForItem(name, price, count) {
    for (var i in cart) {
        if (cart[i].name === name) {
            cart[i].count = count; 
            if (cart[i].count == 0 ) { 
                cart.splice(i, 1); 
            }
            break;
        }               
    }
    saveCart();
};


function removeItemFromCart(name, price, count) {
    for (var i in cart) {
        if (cart[i].name === name ) { 
            cart[i].count --;
            if (cart[i].count == 0 ) { 
                cart.splice(i, 1);   
            }
            break;
        }
    }
    saveCart();
};



function countCart() {
    var totalCount = 0;
    for (var i in cart) {
        totalCount += cart[i].count;
    }
    return totalCount;
};

              
function totalCart() {
    var totalCost = 0;
    for (var i in cart) {
        totalCost += cart[i].price * cart[i].count;
    }
    return totalCost.toFixed(2);
};


function saveCart(){
    localStorage.setItem("shoppingCart", JSON.stringify(cart));
};


function loadCart() {
    cart = JSON.parse(localStorage.getItem("shoppingCart"));

};


loadCart();
displayCart();


$("#show-cart").on("change", ".item-count", function(event){  
                                                            
    var name = $(this).attr("data-name");
    var price = $(this).attr("data-price");
    var count = Number( $(this).val() );

    setCountForItem(name, price, count); 
    displayCart();
});

/*ITEM 2 */
var addToCartButtons = document.getElementsByClassName('add-to-cart2');
for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i];
        button.addEventListener('click', addToCartClicked2);
}

function addToCartClicked2() {
    var parent1 = document.querySelectorAll('#itemName2');
    var name = parent1[0].textContent;
    console.log("1st child of parent1");
    console.log(name)
    var parent2 = document.querySelectorAll('#itemPrice2');
    var price = Number(parent2[0].textContent);
    console.log("1st child of parent2");
    console.log(price);

    addItemToCart(name, price, 1);
    displayCart();
}
/*ITEM 3 */
var addToCartButtons = document.getElementsByClassName('add-to-cart3');
for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i];
        button.addEventListener('click', addToCartClicked3);
}

function addToCartClicked3() {
    var parent1 = document.querySelectorAll('#itemName3');
    var name = parent1[0].textContent;
    console.log("1st child of parent1");
    console.log(name)
    var parent2 = document.querySelectorAll('#itemPrice3');
    var price = Number(parent2[0].textContent);
    console.log("1st child of parent2");
    console.log(price);
    addItemToCart(name, price, 1);
    displayCart();
}
/*ITEM 4 */
var addToCartButtons = document.getElementsByClassName('add-to-cart4');
for (var i = 0; i < addToCartButtons.length; i++) {
      var button = addToCartButtons[i];
      button.addEventListener('click', addToCartClicked4);
}

function addToCartClicked4() {
    var parent1 = document.querySelectorAll('#itemName4');
    var name = parent1[0].textContent;
    console.log("1st child of parent1");
    console.log(name)
    var parent2 = document.querySelectorAll('#itemPrice4');
    var price = Number(parent2[0].textContent);
    console.log("1st child of parent2");
    console.log(price);
    addItemToCart(name, price, 1);
    displayCart();
}`

I tried to copy the remove item code with a clearCartClicked function that I removed from the code but it didn’t work.

Also sorry if the question is worded poorly this is my first question on the site.

Autodesk Platform services : Heatmap is not reflected on the view

I would like to create a heat map based on the following demo
https://github.com/autodesk-platform-services/aps-iot-extensions-demo

However, the heatmap is not showing up.enter image description here

The changes I made in the sample code are as follows
1.Change the following parameters in /public/config.js
APS_MODEL_URN = ‘URN obtained from Translate a Revit File, Generating Room and Space Information’
(Reference:https://github.com/autodesk-platform-services/ aps-tutorial-postman/tree/master/ModelDerivative_07)
APS_MODEL_VIEW = ”

2.Since there was no room information, define the following in /public/extensions/SensorHeatmapsExtension.js

3.Modified the location information of the four sensors in /services/iot.mocked.js so that they are placed inside the cube of the room.

const SENSORS = {
    'sensor-1': {
        name: 'sensor_1-1',// An ID to identify this device
        description: 'rack_1-1_Basic_sensor.',
        groupName: 'Level 2',
        location: {// World coordinates of this device
            x: 70,
            y: 0,
            z: -5
        },
        objectId: 1
    },
    'sensor-2': {
        name: 'sensor_1-2',
        description: 'rack_1-2_Basic_sensor.',
        groupName: 'Level 2',
        location: {
            x: 70,
            y: -30,
            z: -5
        },
        objectId: 2
    },
    'sensor-3': {
        name: 'sensor_1-3',
        description: 'rack_1-3_Basic_sensor.',
        groupName: 'Level 2',
        location: {
            x: 75,
            y: 0,
            z: -5
        },
        objectId: 3
    },
    'sensor-4': {
        name: 'sensor_1-4',
        description: 'rack_1-4_Basic_sensor.',
        groupName: 'Level 2',
        location: {
            x: 75,
            y: -30,
            z: -5
        },
        objectId: 4
    }
};

4.Fixed _setupSurfaceShadingw in /public/extensions/SensorHeatmapsExtension.js as follows

async _setupSurfaceShading(model) {
        if (!this.dataView) {
            return; }
        }
        
        const DataVizCore = Autodesk.DataVisualization.Core;
        const structureInfo = new DataVizCore.ModelStructureInfo(model);
        let levelRoomsMap = await structureInfo.getLevelRoomsMap();

        ///////////////2.room define///////////////
        let room_2 = new DataVizCore.Room(
            2222, //id Room's DbId
            "2F_Room",//name
            Box3(new THREE.Vector3(60, -40. -20), new THREE.Vector3(100, 10, 10))//bounds
        );

        for (const [sensorId, sensor] of this.dataView.getSensors().entries()) {
            if(sensor.objectId >= 1 && sensor.objectId <= 4){
                room_2.addDevice(sensor);
            }
        }        

        levelRoomsMap.addRoomToLevel("Level 2", room_2); }

        /////////////// 4.SurfaceShading ///////////////
        const shadingGroup = new DataVizCore.SurfaceShadingGroup('iot-heatmap');
        const rooms = new Map();

        for (const [sensorId, sensor] of this.dataView.getSensors().entries()) {
            if (!sensor.objectId) {
                continue;
            }
            if (!rooms.has(room_2.id)) {        
                const room = new Autodesk.DataVisualization.Core.SurfaceShadingNode(room_2.name, room_2.id);
                shadingGroup.addChild(room);
                rooms.set(room_2.id, room);
            }
            const room = rooms.get(room_2.id); }
            const types = Array.from(this.dataView.getChannels().keys());
            room.addPoint(new Autodesk.DataVisualization.Core.SurfaceShadingPoint(sensorId, sensor.location, types));
        }
        this._surfaceShadingData = new DataVizCore.SurfaceShadingData();
        this._surfaceShadingData.addChild(shadingGroup);
        this._surfaceShadingData.initialize(model);        
        await this._dataVizExt.setupSurfaceShading(model, this._surfaceShadingData);
        //this._dataVizExt.registerSurfaceShadingColors('temp', [0x00ff00, 0xffff00, 0xff0000]);
    }

react-boostrap Dropdown.Item custom jsx on clicking the item the dropdown does not close

i am trying to create a drop-down component where the user on clicking on a custom item, some code will be executed and then the dropdown will close.

Here is an example of what i am trying to achieve.
https://codesandbox.io/s/react-bootstrapp-checkbox-dropdown-entcq

I am using react-bootstrap and react-bootstrap dropdown (https://react-bootstrap.github.io/components/dropdowns/).

Thank you in advance,
Andreas

White square in header HTML boostrap 5

Im having issues with one webstie that Im creating. It is a form created by Boostrap 5. Im trying to make it responsive as I can

The big problem that Im having is that I cant change the white corner of the next picture when I make the screen smaller.

Image 1

I know that my code is not perfect but I need to understound what is going on here. Thanks for all

HTML:

    <!DOCTYPE html>
    <!-- saved from url=(0031)https://payments.idiomasgc.com/ -->
    <html lang="es"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap demo</title>
        <link href="./Form_academia_files/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
        <!-- Custom styles for this template -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link href="/Formulario_COPIA/Formulario/style_form.css" rel="stylesheet">
        <script src="comp.js"></script>
      </head>
    
    
    
    
      <body class="bg-light">
        
        <header class="p-3 text" style="background-color: #0f6796; height: 100%;">
          <div class="container">
            <div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
              <a href="https://payments.idiomasgc.com/" class="d-flex align-items-center mb-2 mb-lg-0 text-white text-decoration-none">
                <img class="img" src="/Formulario_COPIA/images/Logo_Academia.png">
              </a>
            </div>
          </div>
        </header>
    
    
        <div class="container formulario">
          <form method="POST" action="/Formulario_COPIA/Generar_Pago/generar_pago.php" onsubmit="return validarFormulario()">
              <div class="row g-3">
                <div class="col-md-6">
    
                  <div class="nombre">
                      <label class="texto" for="nombre" class="form-label">Nombre</label>
                    <input type="text" class="form-control" id="nombre" name="nombre" placeholder="" required>
                    <div class="invalid-feedback">
                      Se requiero un nombre válido.
                    </div>
                  </div>
    
                  <div class="email">
                    <label pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-][email protected][a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/"
                    required class="texto" for="email" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email" name="email" placeholder="[email protected]" required>
                    <div class="invalid-feedback">
                      Se requiere un email válido.
                    </div>
                  </div>
    
                  <div>
                    <label class="texto" for="referencia" class="form-label">Referencia</label>
                    <input type="text" class="form-control" id="referencia" name="referencia" placeholder="R2556554" required="">
                    <div class="invalid-feedback">
                      Se requiere una referencia.
                    </div>
                  </div>
    
                </div>
    
                <div class="col-md-6">
                  <div class="apellidos">
                      <label class="texto" for="apellidos" class="form-label">Apellidos</label>
                      <input type="text" class="form-control" id="apellidos" name="apellidos" placeholder="" required="">
                      <div class="invalid-feedback">
                        Se requiere un apellido válido.
                      </div>
                  </div>
    
                  <div class="telefono">
                    <label class="texto" for="telefono" class="form-label">Teléfono</label>
                    <input type="text" class="form-control" id="telefono" name="telefono" placeholder="612345678" required="">
                    <div class="invalid-feedback">
                      Se requiere un teléfono válido.
                    </div>
                  </div>
    
                  <div>
                    <label class="texto" for="importe" class="form-label">Importe</label>
                    <input type="text" class="form-control" id="importe" name="importe" placeholder="100.65" required="">
                    <div class="invalid-feedback">
                      Se requiere un importe.
                    </div>
                  </div>
    
                </div>
                  
              </div>
    
              <hr class="my-4 barra">
    
              <div class="row">
                <div class="col-sm-4">
                
                </div>
                <div class="col-md-3">
                  <button class="boton btn btn-primary btn-lg" type="submit" >CONTINUAR</button>
                </div>
                <div class="col-sm-4">
                  
                </div>
              </div>
    
              
                  
          </form>
            <script src="./Form_academia_files/bootstrap.bundle.min.js.descarga" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
        </div>
     
      </body>
    
    </html>

CSS:

    *{
        padding: 0;
        margin: 0;
        box-sizing: border-box;
    }
    
    .texto{
        font-size: 25px;
        padding: 10px;
        margin-left: -10px;
    }
    .form-control{
        width: 60%;
    }
    header{
        height: 90px;
    }
    .barra{
        margin-right: 20%;
    }
    .formulario{
        margin: 0 auto;
        margin-top: 5%;
        margin-right: 5%;
    
        
    }
    .boton{
       
        margin: 0 auto;
        margin-left: -13%;
        height: 100%;
        width: 80%;
    
        background-color: #54b0df;
        border: 0px;
        border-radius: 100px;
    
        line-height: 1;
        letter-spacing: 1px;
        font-weight: 500;
    
       
    }
    .row{
        max-width: 100%;
    }
    .boton:hover{
       background-color: #f4bc27;
    }
    @media screen and (max-width: 760px) {
        .formulario {
          margin-left: 100px;
        }
        .barra{
            margin-right: 
            40%;
        }
        .boton{
            margin-left: 0%;
            width: 60%;
        }
      }

Use JavaScript Code to run Puppeteer from Laravel Controller

I am using Puppeteer to launch a browser from a laravel controller, however i don’t know how to run the JavaScript code from the controller

My function looks like this:

$script = <<<SCRIPT
    const puppeteer = require('puppeteer');
    (async () => {
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        await page.goto('http://my-url.com');
        const button = await page.$('button#button');
        await button.evaluate( button => button.click() );
        await page.waitForTimeout(5000);
        ...
        await browser.close();
    })();
    SCRIPT;
$process = new Process(['node', '-e', $script]);
$process->run();
$output = $process->getOutput();

When i try to run just this part of the code in the node shell:

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({headless: false});     
    const page = await browser.newPage();
    await page.goto('http://my-url.com');
    const button = await page.$('button#button');
    await button.evaluate( button => button.click() );
    await page.waitForTimeout(5000);
    ...
    await browser.close();
})();

it works fine and I can also see a browser being opened. When I try to run the whole function it doesn’t work. SO I presume that the way i’m running the JS code in the controller is wrong.

How to prvent XSS attack in html output tag? [duplicate]

I’m new to html, and I’m trying to prvent XSS attack in html output tag like

.
for example here is a some simple html code to text XSS hacking

<!DOCTYPE html>
<html>
  <head>
    <link rel="icon" type="image/x-icon" href="icon.png">
  </head>
<body>
  <style>
    
    #edit {
      position: absolute;
      left: 50%;
      top: 90%;
      transform: translate(-50%, -50%);
      width: 250px;
      height: 50px;
      background-color: #34495E;
      font-size: 18px;
      color: white;
      
    }

    #texta {
      height: 90%;
      width: 100%;
    }
  </style>
  
  <?php
  $myfile = fopen("text", "r+") or die("Unable to open file!");
  if (filesize("text") == 0) {
      $con = null ;
  } else {
      $con = fread($myfile,filesize("text"));
  }
  
  ?>
  <p><?php echo$con; ?></p>

  <form action="save.php" method="post">
    <textarea id="texta" name="txt" rows="30" cols="150"><?php echo $con; ?></textarea>

    <input type="Submit" id= "edit" value="Save">
  </form>
  

</body>
</html>

and here is the save.php which save the text in textarea.

<?php

$text = $_POST["txt"];
$file = fopen("text", "w+");
fwrite($file, $text);
fclose($file);
header("location: index.php");
die();
?>

I hacked it with XSS so easly, what should I add to the code to prevent XSS hack?

esle condition not work in foreach loop php

my code:

$customers='[
 {
  "id": 1,
  "name": "sara",
  "phone": 1100,
  "mobile": 1111
 },
 {
  "id": 2,
  "name": "ben",
  "phone": 2200,
  "mobile": 2222
 }
]';
$data = json_decode($customers, true);
foreach($data as $a){
    if($a['name'] == 'sara'){
        $phone = $a['phone'];
        $mobile = $a['mobile'];
        echo "sara's phone is $phone";
        echo "sara's mobile is $mobile";
    }
    else{
    echo "No customer found with this name";
    }
    }

my problem is:
just else part is working and if condition is not working but when i remove else part, if part is working good.
can you help me??