threejs changing texture on scroll

hey guys im new to threejs and im trying to change the texture of my animated model while on scroll, but i got this error GLTFLoader.js:1948 THREE.GLTFLoader: Custom UV set 1 for texture metalnessMap not yet supported. is there any reason why? is there any way to change textures on scroll? currently im using https://sketchfab.com/3d-models/tyrannosaurus-rex-9d3a3e42c0054c35aa39c3ee07388d16 gltf model. thanks in advance.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        position: fixed; top: 0; left: 0;

      }
      div#test2 {
  height: 5000px;
}
    </style>
  </head>
  

  <body>
    <script type="module">
        import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
        
        import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
        import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/GLTFLoader.js';
        import { RGBELoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/RGBELoader.js';
        
        var container, controls;
        var camera, scene, renderer, mixer, clock;
        var obj , material , texture
        
        init();
        animate();
        
        function init() {
        
          container = document.getElementById( 'test' );
          document.body.appendChild( container );
          
          

          camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.01, 1000 );
        //   camera.position.set(0, 5, 30);
          camera.position.x = 0
          camera.position.y = 5
          camera.position.z = 10 


        
          scene = new THREE.Scene();
          scene.background = new THREE.Color(0xffffff);
          var light = new THREE.HemisphereLight(0xffffff,0x000000,10);
          scene.add(light);
    
         var texture = new THREE.MeshMatcapMaterial()

         var matcapTexture = new THREE.TextureLoader().load('purple.jpg')

         var texture = new THREE.MeshMatcapMaterial( {map: matcapTexture})

         console.log(texture)

        

          clock = new THREE.Clock(); 
        
              // model
          
              var loader = new GLTFLoader();
              loader.load( 'scene.gltf', function ( gltf ) {
                
                var matcapTexture = new THREE.TextureLoader().load('purple.jpg')
                var texture = new THREE.MeshMatcapMaterial( {matcap: matcapTexture})



                obj = scene.add( gltf.scene );
        
                mixer = new THREE.AnimationMixer( gltf.scene );
                
                gltf.animations.forEach( ( clip ) => {
                  
                    mixer.clipAction( clip ).play();
                  
                } );
        
              } );


        
        
          renderer = new THREE.WebGLRenderer( { antialias: true } );
          renderer.setPixelRatio( window.devicePixelRatio );
          renderer.setSize( window.innerWidth, window.innerHeight );
          renderer.toneMapping = THREE.ACESFilmicToneMapping;
          renderer.toneMappingExposure = 0.8;
          renderer.outputEncoding = THREE.sRGBEncoding;
          container.appendChild( renderer.domElement );
        

          function rotateFunction() {
        obj.rotation.y += 0.02;        
        console.log(obj.rotation.y)
        
      }

      document.addEventListener('scroll', function(e) { rotateFunction() });


        
        }
        function onWindowResize() {
          camera.aspect = window.innerWidth / window.innerHeight;
          camera.updateProjectionMatrix();
        
          renderer.setSize( window.innerWidth, window.innerHeight );
        }
        
        //
        
        function animate() {
          requestAnimationFrame( animate );
          var delta = clock.getDelta();
          if ( mixer ) mixer.update( delta );
          renderer.render( scene, camera );
        
        }

        function adjustCamera() {              
    var t = scrollY / (5000 - innerHeight);
    console.log(t)
    // t is 0 to 1

        camera.position.z = 10 + 5 * t;


        }

        document.addEventListener('scroll', function(e) { adjustCamera() });

        function changeColor() {
            
            obj.material = texture
                
                console.log(obj)

        }

        document.addEventListener('scroll', function(e) { changeColor() });




        </script>
  </body>
  <div id="test">

  </div>

  <div id="test2">

    testing121

  </div>

</html>

typescript version mismatch

My project has a structure like this:

workspace
  |__pkg1
      |__tsconfig.json
      |__package.json
      |__ts/
  |__pkg2
      |__tsconfig.json
      |__package.json
      |__ts/
  |__lerna.json
  |__package.json
  |__tsconfig.json

In workspace/package.json, I specified the typescript version to be “^4.2.3”. To install the dependency for all packages, run the command under workspace directory:

npm install & lerna bootstrap && lerna run build

“lerna bootstrap” will install all the dependencies for pkg1 and pkg2, “lerna run build” (equivalent to run “npx tsc” in pkg1 and pkg2) will compile typescript in ts/ folder from pkg1 and pkg2. It turned out the tsc version in workspace directory is indeed 4.2.3, but in pkg1 and pkg2, the typescript version is 4.5.2

cd pkg1 && npx tsc -v # output is Version 4.5.2

I have tried (1) to change “^4.2.3” to “4.2.3” in workspace/package.json, (2) specify typescript version explicitly in package.json from pkg1 and pkg2. However, neither of them work. How can I fix it? In practice, I have multiple pkgs, so I don’t want to install typescript one by one in each of the package directory.

Vue.Js, Nuxt.js Multi-steps form – how to presist data on page reload

I have a 3-steps form, Now I’m using 3 diffrenet pages for each step. each step requires a submit to the backend for doing some validations and calculations that is then send to the next step.

The problem is, say that a use filled the first step and go to the second step, if he reloads the page on the 2nd step, the data from the first step will be removed from the Vuex store, and on the last step when he submit the form he will get an error because that data from the first step is no longer availabe on the Vuex store. also If he press the back button on any step, the form on the previous step will be cleared out and the data will not be there.

I can use localStorage and save the data for each step on it, but the problem with this appraoch is some data are sensitive and I don’t want to store sensitive data on localStorage. the second problem with this approach is the data will always be in the form and will not be cleared if the user closes the browser or anything like that.

What is a good way to fix this issues ?

ASP .Net Update Panel partial postbacks stop working when using Javascript window.history.pushState() in front end

I have a business requirement where all page URLs should be hidden so the user doesn’t actually know what page they are on when browsing.

I am using window.history.pushState(‘string’, ‘My Software’, ‘/MyPage’) on all my pages to acheive this. It works fine i.e. all links on the site appear like mysite.com/MyPage. But, whenever we use an update panel for things like modal popup viewers and other things that cause a partial postback, none of that stuff works.

I am using Visual Studio 2010 + ASP.NET 4 Webforms.

Table data does not update when array is updated

I’m working on a data table with Alpine.js, but I’m not able to update the data when the source array is updated.

If I click on any column, my script goes to the database and brings up new sorted data. This works fine, the array is updated, the table is also updated with new data.

The problem is in the function to load more data. When I click the load more data button, the script goes to the database, brings up new data, updates the source array, but the update doesn’t reflect on the table.

Could you help me to discover my mistake?

Load more data

loadMore() {
    this.setSkip(this.getSkip() + this.getLimit());
    this.getData();
},

Get data

getData() {

    let _token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    let url = '/api/users/get-data';

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': _token
        },
        body: JSON.stringify({
            orderBy : this.getColumn(),
            direction : this.getDirection(),
            skip: this.getSkip(),
            limit: this.getLimit()
        })
    })

    //.then(response => response.json())
    .then(function(response) {
        return response.json();
    })

    .then(result => {
        this.stagingData = result;
        this.prepareData(this.stagingData);
    })

    .catch((e) => {
        console.log(e);
    })
},

Prepare data

prepareData(data) {

    if (this.getSkip() > 0) {
        this.users = [...this.users, ...data];
    }

    else {
        this.users = data;
    }

    this.users.forEach(user => {
        console.log(user.id + '-' + user.name);
    });
},

Blade template

<div class="table-responsive overlay-scrollbars" x-data="dataTable()" x-cloak>
    <x-table.table>
        <x-table.table-head>
        </x-table.table-head>

        <x-table.table-body class="list" id="table-users-body">
            <template x-for="user in users" :key="user.id">
                <x-table.table-row class="btn-reveal-trigger">
                    <x-table.table-body-td class="id">
                        <a href="#" class="" data-bs-toggle="modal" data-bs-target="#form-user" @click="$dispatch('edituser', user.id)" x-text="user.id">
                        </a>
                    </x-table.table-body-td>
                    <x-table.table-body-td class="name white-space-nowrap">
                        <div class="d-flex d-flex align-items-center">
                            <h5 class="mb-0 fs--1" x-text="user.name"></h5>
                        </div>
                    </x-table.table-body-td>
                </x-table.table-row>
            </template>
        </x-table.table-body>
    </x-table.table>
</div>

All js (alpine) code

function dataTable() {
    return {

        orderByColumn: 'created_at',
        directionColumn: 'desc',
        stagingData: '',
        users: '',
        data: '',
        limit: 3,
        skip: 0,

        init() {
            this.data = @json($users);
            this.users = this.data.data;
        },

        getSkip() {
            return this.skip;
        },

        setSkip(val) {
            this.skip = val;
        },

        getLimit() {
            return this.limit;
        },

        setLimit(val) {
            this.limit = val;
        },

        getColumn() {
            return this.orderByColumn;
        },

        setColumn(val) {
            this.orderByColumn = val;
        },

        setDirection(val) {
            this.directionColumn = val;
        },

        getDirection() {
            return this.directionColumn;
        },

        toggleDirection(val) {

            let column = document.querySelector('.' + this.getColumn());
            column.classList.remove('desc');
            column.classList.remove('asc');
            column.classList.add('sort');
            this.setColumn(val);

            if (this.getDirection() == 'desc') {

                let newColumn = document.querySelector('.' + val);
                newColumn.classList.remove('desc');
                newColumn.classList.remove('sort');
                newColumn.classList.add('asc')
                this.setDirection('asc');
            }

            else {
                let newColumn = document.querySelector('.' + val);
                newColumn.classList.remove('asc');
                newColumn.classList.remove('sort');
                newColumn.classList.add('desc');
                this.setDirection('desc');
            }
        },

        orderBy(column) {
            this.toggleDirection(column);
            this.getData();
        },

        getData() {

            let _token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            let url = '/api/users/get-data';

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': _token
                },
                body: JSON.stringify({
                    orderBy : this.getColumn(),
                    direction : this.getDirection(),
                    skip: this.getSkip(),
                    limit: this.getLimit()
                })
            })

            //.then(response => response.json())
            .then(function(response) {
                return response.json();
            })

            .then(result => {
                this.stagingData = result;
                this.prepareData(this.stagingData);
            })

            .catch((e) => {
                console.log(e);
            })
        },

        loadMore() {
            this.setSkip(this.getSkip() + this.getLimit());
            this.getData();
        },

        prepareData(data) {

            if (this.getSkip() > 0) {

                // Array.prototype.push.apply(this.users, data);
                // this.users.push(...data);
                // this.users = arr3;

                this.users = [...this.users, ...data];
            }

            else {
                this.users = data;
            }

            this.users.forEach(user => {
                console.log(user.id + '-' + user.name);
            });
        },
    }
}

Using Chart.js with SvelteKit

I’m trying to use Chart.js with SvelteKit. In development mode everything works fine, but when I try to build the project I get the following error.

Directory import 'C:directorynode_moduleschart.jsauto' is not supported resolving ES modules imported from C:directory.svelte-kitoutputserverapp.js

Did you mean to import chart.js/auto/auto.js?

Importing the Chart.js module with an exact path is not a good idea, and only introduces more errors.

I am using @sveltejs/adapter-netlify as my adapter in svelte.config.js, but I get the same error if I run the preview of my build.

I also added the following options to svelte.config.js, but it doesn’t seem to make any difference either way:

vite: {
            build: {
                rollupOptions: {
                    // make sure to externalize deps that shouldn't be bundled
                    // into your library
                    external: ['chart.js/auto/auto.js'],
                    output: {
                        // Provide global variables to use in the UMD build
                        // for externalized deps
                        globals: {
                            'chart.js/auto/auto.js': 'chart.js/auto/auto.js'
                        }
                    }
                }
            }
        }

ExcelJs dynamic hyperlinks not routing

I created a workbook in Exceljs and added some worksheets dynamically do them. Basically I have a master worksheet that is the first thing you see when you open it up. However, I’ve also created player profiles for each person in my initial table. I’m trying to link them up with this piece of code.

    team.forEach((e, index) => {
      console.log(`--- Writing ${e.name} ---`)

      worksheet.addRow({
        teamName: e.teamName,
        name: e.name,
        weight: e.weight,
        wins: e.wins,
        losses: e.losses,
        profile: {
          text: 'This Profile',
          hyperlink: `${e.name}`
        }
      })

And unfortunately, this is just showing the text This Profile and it isn’t able to be clicked on. Each of my worksheets are just the names of the people apart of the team. I am not sure if there is special syntax I need to add.

Here is how I am naming my workbook. I see all of the player profiles being created, just the hyperlinks aren’t working.

async function writePlayerProfile(e, workbook) {
  let worksheet = workbook.addWorksheet(`${e.name}`)

How to enter the one-time password that comes to email with puppeteer

Each time the user logs in, they must enter the one-time password they received by email.

I would like to know the best way to fill in automatically when testing these with puppeteer.

My idea is no longer in headless mode.

(async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();   
    await page.goto('https://example.com/login/');

    await page.waitForFunction(() => {
        // Wait for it to be entered manually.
        const otp = document.getElementById('one-time-password').value;
        return otp.length !== 6;
    });

   //do something 

    await browser.close();
)}();

How to add option groups to the multiselect-dropdown.js plugin?

I’m using multiselect-dropdown.js plugin to customize my select tag. It run’s perfectly but when I add an optiongroup it will not show. Is there a solution to show the option group label without the checkbox? I just want to add the optiongroup label only. Cause right now, the optiongroup is not showing.

var style = document.createElement('style');
style.setAttribute("id","multiselect_dropdown_styles");
style.innerHTML = `
.multiselect-dropdown{
  display: inline-block;
  padding: 2px 5px 0px 5px;
  border-radius: 4px;
  border: solid 1px #ced4da;
  background-color: white;
  position: relative;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right .75rem center;
  background-size: 16px 12px;
}
.multiselect-dropdown span.optext, .multiselect-dropdown span.placeholder{
  margin-right:0.5em; 
  margin-bottom:3px;
  padding:1px 0; 
  border-radius: 4px; 
  display:inline-block;
}
.multiselect-dropdown span.optext{
  background-color:lightgray;
  padding:1px 0.75em; 
}
.multiselect-dropdown span.placeholder{
  color:#ced4da;
}
.multiselect-dropdown-list-wrapper{
  box-shadow: gray 0 3px 8px;
  z-index: 100;
  padding:2px;
  border-radius: 4px;
  border: solid 1px #ced4da;
  display: none;
  margin: -1px;
  position: absolute;
  top:0;
  left: 0;
  right: 0;
  background: white;
}
.multiselect-dropdown-list-wrapper .multiselect-dropdown-search{
  margin-bottom:5px;
}
.multiselect-dropdown-list{
  padding:2px;
  height: 15rem;
  overflow-y:auto;
  overflow-x: hidden;
}
.multiselect-dropdown-list::-webkit-scrollbar {
  width: 6px;
}
.multiselect-dropdown-list::-webkit-scrollbar-thumb {
  background-color: #bec4ca;
  border-radius:3px;
}

.multiselect-dropdown-list div{
  padding: 5px;
}
.multiselect-dropdown-list input{
  height: 1.15em;
  width: 1.15em;
  margin-right: 0.35em;  
}
.multiselect-dropdown-list div.checked{
}
.multiselect-dropdown-list div:hover{
  background-color: #ced4da;
}
.multiselect-dropdown span.maxselected {width:100%;}
.multiselect-dropdown-all-selector {border-bottom:solid 1px #999;}
`;
document.head.appendChild(style);

function MultiselectDropdown(options){
  var config={
    search:true,
    height:'15rem',
    placeholder:'select',
    txtSelected:'selected',
    txtAll:'All',
    ...options
  };
  function newEl(tag,attrs){
    var e=document.createElement(tag);
    if(attrs!==undefined) Object.keys(attrs).forEach(k=>{
      if(k==='class') { Array.isArray(attrs[k]) ? attrs[k].forEach(o=>o!==''?e.classList.add(o):0) : (attrs[k]!==''?e.classList.add(attrs[k]):0)}
      else if(k==='style'){  
        Object.keys(attrs[k]).forEach(ks=>{
          e.style[ks]=attrs[k][ks];
        });
       }
      else if(k==='text'){attrs[k]===''?e.innerHTML='&nbsp;':e.innerText=attrs[k]}
      else e[k]=attrs[k];
    });
    return e;
  }

  
  document.querySelectorAll("select[multiple]").forEach((el,k)=>{
    
    var div=newEl('div',{class:'multiselect-dropdown',style:{width:config.style?.width??el.clientWidth+'px',padding:config.style?.padding??''}});
    el.style.display='none';
    el.parentNode.insertBefore(div,el.nextSibling);
    var listWrap=newEl('div',{class:'multiselect-dropdown-list-wrapper'});
    var list=newEl('div',{class:'multiselect-dropdown-list',style:{height:config.height}});
    var search=newEl('input',{class:['multiselect-dropdown-search'].concat([config.searchInput?.class??'form-control']),style:{width:'100%',display:el.attributes['multiselect-search']?.value==='true'?'block':'none'},placeholder:'search'});
    listWrap.appendChild(search);
    div.appendChild(listWrap);
    listWrap.appendChild(list);

    el.loadOptions=()=>{
      list.innerHTML='';
      
      if(el.attributes['multiselect-select-all']?.value=='true'){
        var op=newEl('div',{class:'multiselect-dropdown-all-selector'})
        var ic=newEl('input',{type:'checkbox'});
        op.appendChild(ic);
        op.appendChild(newEl('label',{text:config.txtAll}));
  
        op.addEventListener('click',()=>{
          op.classList.toggle('checked');
          op.querySelector("input").checked=!op.querySelector("input").checked;
          
          var ch=op.querySelector("input").checked;
          list.querySelectorAll("input").forEach(i=>i.checked=ch);
          Array.from(el.options).map(x=>x.selected=ch);
  
          el.dispatchEvent(new Event('change'));
        });
        ic.addEventListener('click',(ev)=>{
          ic.checked=!ic.checked;
        });
  
        list.appendChild(op);
      }

      Array.from(el.options).map(o=>{
        var op=newEl('div',{class:o.selected?'checked':'',optEl:o})
        var ic=newEl('input',{type:'checkbox',checked:o.selected});
        op.appendChild(ic);
        op.appendChild(newEl('label',{text:o.text}));

        op.addEventListener('click',()=>{
          op.classList.toggle('checked');
          op.querySelector("input").checked=!op.querySelector("input").checked;
          op.optEl.selected=!!!op.optEl.selected;
          el.dispatchEvent(new Event('change'));
        });
        ic.addEventListener('click',(ev)=>{
          ic.checked=!ic.checked;
        });

        list.appendChild(op);
      });
      div.listEl=listWrap;

      div.refresh=()=>{
        div.querySelectorAll('span.optext, span.placeholder').forEach(t=>div.removeChild(t));
        var sels=Array.from(el.selectedOptions);
        if(sels.length>(el.attributes['multiselect-max-items']?.value??5)){
          div.appendChild(newEl('span',{class:['optext','maxselected'],text:sels.length+' '+config.txtSelected}));          
        }
        else{
          sels.map(x=>{
            var c=newEl('span',{class:'optext',text:x.text});
            div.appendChild(c);
          });
        }
        if(0==el.selectedOptions.length) div.appendChild(newEl('span',{class:'placeholder',text:el.attributes['placeholder']?.value??config.placeholder}));
      };
      div.refresh();
    }
    el.loadOptions();
    
    search.addEventListener('input',()=>{
      list.querySelectorAll("div").forEach(d=>{
        var txt=d.querySelector("label").innerText.toUpperCase();
        d.style.display=txt.includes(search.value.toUpperCase())?'block':'none';
      });
    });

    div.addEventListener('click',()=>{
      div.listEl.style.display='block';
      search.focus();
      search.select();
    });
    
    document.addEventListener('click', function(event) {
      if (!div.contains(event.target)) {
        listWrap.style.display='none';
        div.refresh();
      }
    });    
  });
}

window.addEventListener('load',()=>{
  MultiselectDropdown(window.MultiselectDropdownOptions);
});
select {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple multiselect-search="true" multiselect-select-all="true" multiselect-max-items="3" class="w-full mt-8 no-border">
  <optgroup label="Tenants">
    <option>Create Proposal</option>
    <option>Retrieve Customer Data</option>
    <option>Edit Dependant Data</option>
  </optgroup>

  <optgroup label="User">
    <option>User 1</option>
    <option>User 2</option>
    <option>User 3</option>
  </optgroup>
</select>

Is it possible to use a bucket instead of a local folder when using WebTorrent?

I’m building a NodeJS Torrent client (for fun) using WebTorrent and Supabase in order to save users, some data and also I have a bucket with some available storage.
My question is if it’s possible to download a torrent to the Supabase bucket and having the torrent files online instead of a local folder on my PC.
Here is the code I’m using to manage torrents downloads:

const WebTorrent = require('webtorrent');

const client = new WebTorrent();

const magnetURI = 'magnet: ...';

client.add(magnetURI, { path: 'i would like to use my bucket here' }, function (torrent) {
  console.log(torrent);
});

And this is the code I’m using tu upload something to my bucket:

const { data, error } = await supabase.storage
  .from('files')
  .upload(fileFromTorrent)

Cannot read properties of null (reading ‘ShadowRoot’) – Java and Selenium

I am trying to web scrape using Java and Selenium but for one part of what I need to web scrape, it requires me to access a shadow DOM element. I am using Javascript executor to access it and I am entering the querySelector snippet needed to retrieve what I am looking for but I am getting a “Cannot read properties of null (reading ‘ShadowRoot’)” error. Is anyone familiar with this and how to solve it?

Here is my code snippet:

 String pagePdfUrl = (String) js.executeScript("document.querySelector('pdf-viewer').shadowRoot.getElementById('content').querySelector('embed').getAttribute('original-url')");

js is the JavascriptExectuor variable.

Thank you!

How can bots ping someone after a member gets a role? Discord js v12

So i want the bot ping someone, after member get some role

this is my code

client.on('guildMemberUpdate', async(member) => {
    const memberRole = message.guild.roles.cache.find((role) => role.id ==='role id');//and this is for the role id, so the bot knows this role and the bot automatically pings someone to the channel i want

const Channel = member.guild.channels.cache.get('channel id') //and this channel id, i want the bot ping someone in this channel
    Channel.send(`here lmao <@${member.id}> `)
    .then((member)=> member.delete({
        timeout: 10000 //and this i purposely made this to look like a ghost ping
    }));
})

I know this code looks messy (: , so i’m asking for your help
Thank u!

Heroku app with node.js block CORS from time to time

I wanted to deploy a node.js backend in Heroku, working on the front end with react deployed on Vercel. From time to time, the front request to heroku backend are blocked by CORS policy, just like this:

Access to XMLHttpRequest at ‘https://pokedex-deployment-luis.herokuapp.com/pokemons/11’ from origin ‘https://react-node-pokedex-git-dev-luisea97.vercel.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Is strange for me, because NOT EVERY CALL TO THE BACKEND ARE BLOCKED, ONLY FROM TIME TO TIME. For example, if I reload the page 2 or 3 times it successfully make request to backend without CORS blocking.

I have my code in node like this:

index.js:


const server = require('./src/app.js');
const { conn } = require('./src/db.js');

// Syncing all the models at once.
conn.sync({ force: false }).then(
async () => {
 await server.listen(process.env.PORT, () => {
    console.log('%s listening at ' + process.env.PORT); // eslint-disable-line no-console
  });
});

app.js:

const express = require('express');
const morgan = require('morgan');
const routes = require('./routes/index.js');
const cors = require('cors')
require('./db.js');

const server = express();

server.name = 'API';

server.use(morgan('dev'));
server.use(express.json());


//Cors
server.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); // update to match the domain you will make the request from
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});


server.use('/', routes);

// Error catching endware.
server.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  const status = err.status || 500;
  const message = err.message || err;
  console.error(err);
  res.status(status).send(message);
});

module.exports = server;

I’ve tried manage CORS like this:

server.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); // update to match the domain you will make the request from
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

like this other one way:

//Cors
server.use(cors())
/* server.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); // update to match the domain you will make the request from
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
}); */

like this other way:

server.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'https://react-node-pokedex-git-dev-luisea97.vercel.app/'); // with vercel production app's domain
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
  next();
});

or even like this:

server.use(cors())
server.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); // update to match the domain you will make the request from
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

with no success

Can anyone tell me what am I missing or doing wrong?
Thanks in advance:)