How can I get a data from get request from pure js?

I have a simple express app, and I am trying to listen to app.get() router from JS file but I am getting Error here:

    fetch('/').then(function(response) {
        return response.json();
    }).then(function(data) {
      console.log(data);
    }).catch(function() {
      console.log("Error");
    });

app.js

app.get('/',(req,res)){
// some data fetched from api
res.send(data)
}

How can i use fetch to get results from get request from pure JS file? TIA!

WebView Desktop Mode Error Open Link in Browser

Help me to solve my exercise. I make WebView app that showing WhatsApp Web QR Code in Desktop Mode, QR Code not showing in Mobile View.

I have success to open WhatsApp Web in WebView in Desktop Mode. But when you click a link in it, it changes to Mobile View. My idea is to open link in browser, not in WebView. Everythings fine, but when you close the app then open it again, it directly open WhatsApp Web in browser.

This is my app source code, including :

  • progress bar
  • ads
  • desktop mode (user agent string)
  • open link in browser

Can you help me?

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

public class Dashboard extends AppCompatActivity {

    private WebView myWebView;
    private ProgressBar progressBar;
    private AdView mAdView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        progressBar = findViewById(R.id.progressbar_in);
        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("https://web.whatsapp.com");

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(false);
        myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        myWebView.setScrollbarFadingEnabled(false);

        //myWebView.setWebViewClient(webViewClient);
        myWebView.setWebViewClient(new MyWebViewClient());


        String userAgent = webSettings.getUserAgentString();

        try {
            String androidString = webSettings.getUserAgentString().
                    substring(userAgent.indexOf("("), userAgent.indexOf(")") + 1);

            userAgent = webSettings.getUserAgentString().replace(androidString, "X11; Linux x86_64");

        } catch (Exception e) {
            e.printStackTrace();
        }

        webSettings.setUserAgentString(userAgent);
        myWebView.reload();

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

    }

   // WebViewClient webViewClient = new WebViewClient() {
   public final class MyWebViewClient extends WebViewClient {

       @Override
       public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
           Intent i = new Intent(Intent.ACTION_VIEW, request.getUrl());
           startActivity(i);
           return true;
       }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            progressBar.setVisibility(View.VISIBLE);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(View.GONE);
        }
    };

        @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

}

Does React Context API work with browser back?

If I have multiple components that I navigate between and I use React context object in all the components for state management.
So for e.g. if I navigate from /route1 (Component1) to /route2 (Component2) and I use CommonContext object in both. In /route2 (Component2), I update the CommonContext and then go back to /route1 (Component1). Would the updated state be reflected in Component1 now. So basically, the question is
does React Context API work with browser back ?

How to create a global string in a vue (webpack) project

In my vue project I have a default image that should show up in places around the app when an image is missing or hasn’t been uploaded yet. I have various class files and component calls that want to use the same image.

What is the best way to create a global variable that I can access from anywhere? I can’t put it in the store because my class files (I’m using vuex-orm) are loaded before the store is declared. I would prefer not to put it in the window because I want to have a single word variable that I can call (defaultImg as opposed to window.my_project.globals.defaultImg). I could put it in .env but I want this to be checked into the repository and the same across environments so that doesn’t seem right either.

What is the best way to provide a simple global string to all files in my vue project?

Dropdown menu transition Bootstrap 5

I’ve been trying to make a height transition in my dropdown menu made in Bootstrap 5 with hover, the transition is not working, any help on this?

html:

<li class="nav-item dropdown position-static me-lg-3">
        <a class="nav-link" role="button">Temas<button type="button" class="btn dropdown-toggle 
            dropdown-toggle-split p-0" data-bs-toggle="dropdown" aria-expanded="false">
        </button></a>
        
        <div class="dropdown-menu">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
          <a class="dropdown-item" href="#">Separated link</a>
          <a class="dropdown-item" href="../default/">Default</a>
          <a class="dropdown-item" href="../united/">United</a>
          <a class="dropdown-item" href="../yeti/">Yeti</a>
          <a class="dropdown-item" href="../default/">Default</a>
          <a class="dropdown-item" href="../united/">United</a>
          <a class="dropdown-item" href="../yeti/">Yeti</a>
          <a class="dropdown-item" href="../default/">Default</a>
          <a class="dropdown-item" href="../united/">United</a>
          <a class="dropdown-item" href="../yeti/">Yeti</a>
          <a class="dropdown-item" href="../default/">Default</a>
          <a class="dropdown-item" href="../united/">United</a>
          <a class="dropdown-item" href="../yeti/">Yeti</a>
          <a class="dropdown-item" href="../default/">Default</a>
          <a class="dropdown-item" href="../united/">United</a>
          <a class="dropdown-item" href="../yeti/">Yeti</a>
        </div>
</li>

CSS

.dropdown .dropdown-menu {
    transform: scaleY(0);    
    transform-origin: top;
    transition: transform 0.26s ease;
 }
    
 .dropdown-menu.show {
      margin-top: 0vh;
      width: 40%;
      margin-left: 38vw;
 }
    
 .dropdown:hover .dropdown-menu {
      display: flex;
      flex-wrap: wrap;
      transform: scaleY(1)
 }
    
 .dropdown-item {
      width: 25% !important;
 }

And this is Jquery function to make the hover work as a click on bootstrap5 dropdown

$('.dropdown').on("mouseenter", () => {
    $('.dropdown > a > button').addClass('show')
    $('.dropdown > a > button').attr("aria-expanded","true");
    $('.dropdown > div').addClass('show')
    $('.dropdown > div').attr("data-bs-popper","none");
  })
  
  $('.dropdown').on("mouseleave", () => {
    $('.dropdown > a > button').removeClass('show')
    $('.dropdown > a > button').attr("aria-expanded","false");
    $('.dropdown > div').removeClass('show')
    $('.dropdown > div').removeAttr("data-bs-popper","none");
  })
});

I alredy try the answers on this question but none of them are working

How to find substring ignoring the data inside comment

I am trying to find substring from an HTML string by ignoring the commented code. I have tried something like below but it is nor giving me expected result , Any pointer will be really appreciated.

let a = `<div data-bind="attr: {id: componentId + 'MasterDetailContainer'}"
     style="height: 100%; width: 100%">

    <!-- master --> <!-- Bug 31793483 adding aria label -->
    <div role="navigation" data-bind="attr: {id: componentId + 'MasterDetailStartDrawer'}">`;
 
let databindIndex =a.indexOf('data-bind');
//Get all the data till next valid starting tag ignoring commented code
let data =a.indexOf(/<ws/g,databindIndex);
console.log(data);

Expected output

`data-bind="attr: {id: componentId + 'MasterDetailContainer'}"
         style="height: 100%; width: 100%">
    
        <!-- master --> <!-- Bug 31793483 adding aria label -->`

Jquery Onclick functions wont work on second datatable’s other pages

I have this datatables on my php but the jquery onclick functions only works properly on the first page but not the others.

the view data using modal works fine and the deleting of data as well but only on the first page

this is my buttons

<button type="button" id="<?php echo $row["Member_ID"]; ?>" class="btn btn-success btn-sm view_member_data">
    <i class="bi bi-eye-fill"></i>
</button>
<button type="button" id="<?php echo $row["Member_ID"]; ?>" class="btn btn-danger btn-sm delete_member_data">
    <i class="bi bi-trash-fill"></i>
</button

the command for viewing and deleting data:

<script>
    $(document).ready(function() {
        $('.delete_member_data').click(function(e) {
            e.preventDefault();
            var employee_id = $(this).attr("id");
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "delete_members.php",
                        method: "post",
                        data: {
                            employee_id: employee_id
                        },
                        success: function(data) {
                            Swal.fire(
                                'Deleted!',
                                'Member successfully deleted.',
                                'success'
                            ).then((result) => {
                                window.location.reload(true);
                            });
                        }
                    });
                }
            })
        });
    });
</script>
<script>
    $(document).ready(function() {
        $('.view_member_data').click(function() {
            var employee_id = $(this).attr("id");
            $.ajax({
                url: "view_member_data.php",
                method: "post",
                data: {
                    employee_id: employee_id
                },
                success: function(data) {
                    $('#employee_detail').html(data);
                    $('#dataModal').modal("show");
                }
            });
        });
    });
</script>

How to recursively copy arrays

I want to recursively produce the vertices (points) of a unit n-hypercube (for the sake of clarity, just a cube here). The idea is to specify the points of the cube by recursively going through the x, y, and z components. Why not just use nested for-loops? Recursion is intrinsically swag. This is my function:

var points = [];

function makeCube(d, point) {
  console.log(d,point);
  
  if(d == 0) {
    points.push(point);
  } else {
    extension1 = [...point];
    extension1.push(0);

    extension2 = [...point];
    extension2.push(1);
    
    makeCube(d - 1, extension1);
    makeCube(d - 1, extension2);
  }
}

I call makeCube(3, []). The console reads this:

[Log] 3 – [] (0) (sketch.js, line 57)
[Log] 2 – [0] (1) (sketch.js, line 57)
[Log] 1 – [0, 0] (2) (sketch.js, line 57)
[Log] 0 – [0, 0, 0] (3) (sketch.js, line 57)
[Log] 0 – [0, 0, 1] (3) (sketch.js, line 57)
[Log] 1 – [0, 0, 1] (3) (sketch.js, line 57)
[Log] 0 – [0, 0, 1, …] (4) (sketch.js, line 57)
etc...

When d is 1, there should only be 2 entries in the array, not 3! When d is 0, there should be 3, not 4. The second array in the lowest level is being carried up a level somehow. I made a point of copying the extension arrays rather than setting them equal to the old one, so I don’t understand what’s going on.

ReactPlayer onClick and controls not working

OnClick not working and controls shows but click play or mute ..etc not working

 {
          useMemo(() =>
          (<>
            {buyList.length > 0 && openBox && 
                <ReactPlayer 
                  url= {`videos/${width > height ? buyList[currentIndex].desktop : buyList[currentIndex].mobile}`}
                  playing   ={openBox && !allStop}
                  loop={false}
                  controls={true}
                  muted={muted}
                  onEnded={handleVideoEnded}
                  width='100%'
                  height='100%'
                  onClick ={openBox}
              />
            }
          </>)
          ,[currentIndex, allStop, muted])
        }

Api inside componentDidUpdate not returning data

I am running an Api inside componentDidUpdate. My code is –

componentDidUpdate(prevProps, nextProps) {
        const getSalaries = async () => {
            console.log("this ran");
            const data = await api.get(
                `/client/${this.props.client.id}/salary`
            );
        };

        if (this.props.client !== prevProps.client) {
            this.props.client.id !== undefined && getSalaries();
        }
    }

The statusCode returned by this request is 200 but there is no data returned. There is nothing wrong with this api. I have checked this on postman. When I console.log(data), it returned following-

{
“data”: “”,
“status”: 200,
“statusText”: “”,
“headers”: {
“access-control-expose-headers”: “Access-Control-Expose-Headers, Content-Disposition”,
“cache-control”: “no-cache, no-store, max-age=0, must-revalidate”,
“expires”: “0”,
“pragma”: “no-cache”
},
“config”: {
“transformRequest”: {},
“transformResponse”: {},
“timeout”: 0,
“xsrfCookieName”: “XSRF-TOKEN”,
“xsrfHeaderName”: “X-XSRF-TOKEN”,
“maxContentLength”: -1,
“headers”: {
“Accept”: “application/json, text/plain, /“,
“Authorization”: “Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJVcGVuZHJhRGhhbWFsYUBrb2l6YWkuY29tIiwibmJmIjoxNjQ5OTg2MDcxLCJVc2VyLlVVSUQiOiI2MjIxZDdlZmM5ZTc3YzAwMDEwOWU1MWMiLCJpc3MiOiJ3d3cua29pemFpLmNvbSIsImV4cCI6MTY1MDAxNDg3M”
},
“method”: “get”,
“url”: “http://34.124.147.12:8181/api/v1/client/6225c701c9e77c00014c6796/salary”
},
“request”: {} }

TypeScript intersection type confusing [duplicate]

I am very confusing about TypeScript intersection, for example:

type A = 1 | 2;
type B = 2 | 3;

type AB = A & B;

type C = { a: 1, b: 2 };
type D = { b: 2, c: 3 };

type CD = A & B;

Type AB returns 2, this is easy to understand, but why CD returns {a: 1, b: 2, c: 3}, from my understanding, CD should returns {b: 2}, because a property only on C and c property only on D.

In making a CRUD api, is there a recommended way to handle “route” syntax involving multiple queries?

I started working on a app that will receive a “route” as json. That is the “route” itself will passed as a string to the server enclosed in a json string. I want to use a CRUD standard way of writing routes to keep things more easily debuggable later. However, as follows by example:

contact            'get all contacts
contact/:id        'get the contact by id

Ugly areas:

contact/:id/jobs            'get the contact and all jobs assigned to contact
contact/:id/jobs/filter     'get the contact and all jobs assigned to contact, 
                            'where those jobs meet a certain criteria (filter)

Now I could avoid the ugly areas via routes on “jobs” by having CRUD routes on “jobs”, which I will. But if I wanted limit returned “jobs” to a specific contact as in the above, is there a way to write CRUD syntax for that without making up new conventions?

This will all be implemented in PHP and Javascript, hence those question tags. But it doesn’t really matter the programming languages involved. I’d appreciate any advice relating to designing routes using a CRUD way. Without any particulars involved on frameworks. Just the formatting (spellings) of routes themselves.