CloudFlare R2 Bucket error with reaching media files from NodeJS

i trying host media/image files on cloudflare r2 bucket. I tried lots of stuff but I still can’t reach bucket from outsite with nodeJS.

How can i fix this code?

My Final Code:

fetch('https://USER_ID.r2.cloudflarestorage.com/PROJECT_NAME/src/thumbs/BLAHBLAH', {
    method: 'GET',
    headers: {
        'Content-Type': 'image/jpeg',
        'Authorization': 'SECRET_KEY_FOR_API',
        'X-Amz-Ac': 'private',
        'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
        'X-Amz-Date': (new Date().toISOString().split(':').join('').split('.')[0] + 'Z').split('-').join(''),
        'X-Amz-Expires': '86400',
        'x-amz-content-sha256': 'UNSIGNED-PAYLOAD',
}}).then(res => res.text()).then(buffer => {
            console.log(buffer);
}).catch(err => {
        console.log(err);
});

JavaScript Object – How to Find the user who has max skills

How to find the user who got maximum number of skills.
How to find the user who got maximum number of skills.
How to find the user who got maximum number of skills.

obj = {
    "Alex": {
        "age": 20,
        "skills": [
            "HTML",
            "CSS",
            "JavaScript"
        ]
    },
    "Daniel": {
        "age": 30,
        "skills": [
            "HTML",
            "CSS",
            "JavaScript",
            "Python"
        ]
    },
    "John": {
        "age": 25,
        "skills": [
            "HTML",
            "CSS",
            "JavaScript",
            "React",
            "Redux",
            "Node.js"
        ]
    }
}

navigator.geolocation.watchPosition() doesn’t log position when phone display is off

Say I have a website with this code:

<script>
const watchID = navigator.geolocation.watchPosition((position) => {
    el = document.querySelector('#log');
    el.innerHTML = el.innerHTML + position.coords.latitude + ',' + position.coords.longitude + '<br>';
});
</script>

<div id="log"></div>

The code runs without issue, on my phone, when the display is on and I’m currently viewing the page in the browser. But if I turn the screen off or go to another app (whilst not closing the browser) I code stops running. It’s like it only runs when it has focus.

Am I correct in assuming that this is the key difference between a mobile app and a webpage?

Programming Language for finding jobs [closed]

I’ll explain my situation:

I am 17 years old and I live in Italy, I was planning to program “seriously” and find jobs as a freelancer. in order to be able to accumulate enough money for the university and my personal expenses.

Which programming language is sought after in the world of work? Or even better: with which language is it possible to diversify programming?

Thank you.
Have a nice day

React Native – Strange error caught – {“line”:25722,”column”:33,”sourceURL”:”http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=

My react native application is running on android virtual device (API 23)

Android Gradle Plugin Version – 7.2.0
Gradle Version – 7.4.2

build.gradle

buildscript {
    ext {
        kotlinVersion = "1.5.0"
        RNNKotlinVersion = kotlinVersion
        buildToolsVersion = "31.0.0"
        minSdkVersion = 23
        compileSdkVersion = 31
        targetSdkVersion = 28
...

}

An http request (http://10.0.2.2:8888/myapp/auth) is made to confirm login to my localhost server.
I get an http response code 500 (email/password is incorrect).
AccessService calls FetchTool to fetch http.
FetchTool throws a new Error(‘incorrect email/password’).
But AccessService receives a ghost different error as described below:

LOG ERROR..:{"line":25722,"column":33,"sourceURL":"http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false&app=com.myapp&modulesOnly=false&runModule=true"}

Why don’t I get the error 500 thrown in FetchTool in AccessService’s catch?

export default class AccessService {

    static confirmLogon(email, password) {

        const login = {
            email: email,
            password: password
        };

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

        const uri = properties.appurl + '/auth';

        return FetchTool.post(uri, headers, login)
            .then(credentials => {
                return credentials;
            })
            .catch(error => {
                // the ghost error is captured here 
                console.log('ERROR..:' + JSON.stringify(error))
                throw error;
            });
    }

}

export default class FetchTool {

    static post(uri, headers, playload) {
        return this.executeRequest(uri, headers, playload, 'POST');
    }

    static executeRequest(uri, headers, playload, method) {

        if (headers['Content-Type'] && headers['Content-Type'] == 'application/json') {
            playload = JSON.stringify(playload);
        }

        const requestInfo = {
            method: method,
            body: playload,
            headers: headers
        }

        //uri = http://10.0.2.2:8888/myapp/auth
        
        return fetch(uri, requestInfo)
            .then(response => {

                if (response.ok) {
                    //some code return json ok
                } else {
                    return response.text()
                        .then(responseText => JSON.parse(responseText))
                        .then(responseObject => {
                            if(responseObject.statusCode === 500) {
                                //the error scenario takes place here
                                throw new Error(JSON.stringify(responseObject)); 
                            } else {
                                // some code
                            }
                        })
                }
            })

    }
    
    
}

spotify web api invalid redirect uri

I’m trying to get a grant code and every time I make a request with my respective clientID and clientSecret I get a 400 response error and the catch statement executes:

Details: invalid_grant Invalid redirect URI

From my perspective its as if

Some posts say that the redirect URI has to be the exact same in the developer dashboard and in the request header but it gives the exact same result.
Here’s my current node.js file:

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const SpotifyWebApi = require("spotify-web-api-node");

const app = express();
app.use(cors());
app.use(bodyParser.json());

app.post("/login", (req, res) => {
    const code = req.body.code;
    const spotifyApi = new SpotifyWebApi({
        redirectUri: "http://localhost:3000/",
        clientId: "someCode",
        clientSecret: "someCode",
    });

    spotifyApi
        .authorizationCodeGrant(code)
        .then((data) => {
            res.json({
                accessToken: data.body.access_token,
                refreshToken: data.body.refresh_token,
                expiresIn: data.body.expires_in,
            });
        })
        .catch((err) => {
            console.log(err)
            res.sendStatus(400);
        });
});

app.listen(3001);

This is the custom hook making the request:

import { useEffect, useState } from "react";
import axios from "axios";

export default function useAuth(code) {
    const [accessToken, setAccessToken] = useState();
    const [refreshToken, setRefreshToken] = useState();
    const [expiresInToken, setExpiresIn] = useState();

    useEffect(() => {
        axios
            .post("http://localhost:3001/login", {
                code,
            })
            .then((res) => {
                window.history.pushState({}, null, "/");
                console.log(res.data);
            })
            .catch(() => {
                window.location = "/";
            });
    }, [code]);
}

Return URL from file uploaded to AWS S3

I have a function that makes an API request containing the URL of a new file I just uploaded to AWS S3.
And I have one function that only upload the file to S3.

I am having issues with returning this URL of the uploaded file.

Here is my code:

  myfunction(){
    let file; // assume the file is already set
    let filename; // assume the filename is already set

    let s3URL =  uploadFile(file, filename);
    console.log(s3URL); // this is returning a ManagedUpload object, I dont know how to get the URL from there
    makeAPIRequest(s3URL);
  }

  async uploadFile(file, fileName) {
    // S3 is from --> import * as S3 from 'aws-sdk/clients/s3';
    const s3 = new S3(
      {
        accessKeyId: 'myaccesskeyid',
        secretAccessKey: 'mysecretaccesskey',
        region: 'us-east-1'
      }
    );

    const params = {
      Bucket: 'my-bucket',
      Key: 'MyDirectory/' + fileName,
      Body: file
    };

    return await s3.upload(params, function(err, data) {
      console.log(err, data);
      return data; // URL is here inside data.Location
    });
  }

Here is the SDK doc with the upload example:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

Thanks in advance 🙂

How to know when the map function ends?

I have a “answersRequest” function, gets the id of the answers it writes to the “b” list

    const answersRequest = () => {
        let b = [];
        answers.map(answer => {
            axios({
                method: 'POST',
                url: 'http://127.0.0.1:8000/api/answers/',
                data: answer
            }).then(resp => {
                b.push(resp.data.id)
            })
        })
    }

And on completion of the map function, the below function needs to be run

const a = () => {setQuestionsBlok([...questionsBlok, {...questionBlokInputs, answers: b}]); setAnswers([])};

but I don’t know how to find out when the map function ends

help me please

navigator.mediaDevices.enumerateDevices() returns non-sensical labels and getUserMedia() seems to always be using the same device

I have a Samsung Galaxy S22 Ultra and I’m trying to use navigator.mediaDevices to (1) list all the cameras and (2) show output from any of the cameras.

Here are the device labels when I list all the cameras on my device:

  • camera2 1, facing front
  • camera2 3, facing front
  • camera2 2, facing back
  • camera2 0, facing back

As I understand it the phone has 5x total cameras:

  • a 108MP wide camera
  • a 12MP ultrawide camera
  • a 10MP telephoto
  • a 10MP periscope telephoto
  • front camera.

So 4x of the cameras are rear facing and 1x is front facing. So why is it that navigator.mediaDevices.enumerateDevices() returns something else completely different?

My next question is… when I use any of the deviceIds that navigator.mediaDevices.getUserMedia() returned I get the front facing camera view on my phone, even if I select a deviceId who’s label is “facing back”. What’s up with that?

Here’s my code:

<script>
navigator.mediaDevices.getUserMedia({video: true});

var getCameraSelection = async () => {
  var devices = await navigator.mediaDevices.enumerateDevices();
  var videoDevices = devices.filter(device => device.kind === 'videoinput');
  const options = videoDevices.map(videoDevice => {
    return `<li><a href="#" onclick="useCamera('${videoDevice.deviceId}')">${videoDevice.label}</a></li>`;
  });
  document.querySelector('#output').innerHTML = '<ul>' + options.join('') + '</ul>';
};

getCameraSelection();

var useCamera = async (deviceId) => {
  const stream = await navigator.mediaDevices.getUserMedia({
    deviceId: deviceId,
    video: true
  });
  var video = document.querySelector('video');
  video.srcObject = stream;
  video.play();
  return false;
};
</script>

<div id="output"></div>
<video autoplay></video>

Inserting fetched API request to your own database

(Beware intense beginner question)

I’m building a project in sveltekit recently, mainly it revolves about requesting data from different api’s based on search criteria, combining it together to produce users desired search results and also have some fun discovering something new for myself, learning along the way.

By looking at a different api documentations I see that in one of them maximal request count in their pricing plan is 50000 a day(and every single api I use have max request count). By doing some quick math I realised that 1000 people could easily achieve that and hit maximum request limit really fast (Not that I’m sure that this many people will visit my site each day).

It made me wonder as a total beginner if I could legally request data constantly, from the chosen api and store it in firebase database (maybe some other database is better option) as json objects. Going that route what would be the most efficient way to do that ? Could I maybe run a script that would request data from api and store them constantly without me doing it to have some requested in my db and by requesting from my db some data, avoid hitting daily limit of requests ?

I may be missing something crucial or this question is ridiculous, I have a feeling that it may be true.
I really tried to look online and basically the concept may be conceivable for me but I can’t find the efficient way to do that. My example may be completely inefficient.

Could someone explain to me if doing something like that is possible and if there is a efficient way to do that ? What should I do/learn/watch/read ?

React redux saga Unexpected token < in JSON at position 0

I was similar questions in stackoverflow but none of those solution is working for me .

So i trying to get get data from api to redux saga and getting this error

Productsaga.js

export function* getProducts() {
    try {
        let data = yield fetch(`http://localhost:3000/shoes`);
        data = yield data.json();
        console.warn("action is called", data)
    }
    catch (error) {
        console.log(error)
    }
}
function* productSaga() {
    yield takeEvery(PRODUCT_LIST, getProducts)
}
export default productSaga

use script JavaScript in contoller laravel

i need to use this script inside a laravel controller. the script uses a facial recognition library to compare the faces that are in the photos. How can I use this code inside a public function?

    const imageUpload = document.getElementById('imageUpload')
Promise.all([
    faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
    faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
    faceapi.nets.ssdMobilenetv1.loadFromUri('/models'),
    faceapi.nets.tinyFaceDetector.loadFromUri('/models')
  ]).then(start)

 
  
  

async function start() {
  
  document.body.append('Loaded')
  imageUpload.addEventListener('change', async () => {
    
    image = await faceapi.bufferToImage(imageUpload.files[0])
    
    const descriptions = []
    const detections1 = await faceapi.detectAllFaces(image).withFaceLandmarks().withFaceDescriptors();
    
    const faceMatcher = new faceapi.FaceMatcher(detections1, 0.6)

    var a = 0;
    const images = [];
    for (var i = 100; i <= 618; i++) {
      let image = 0;
      let img = new Image();
      img.src = 'test/' + i + '.jpeg';
      image = i + '.jpeg';
  
      const results = await faceapi.detectAllFaces(img).withFaceLandmarks().withFaceDescriptors()
      results.forEach(fd => {
        const bestMatch = faceMatcher.findBestMatch(fd.descriptor)

        if (bestMatch.label == "person 1") {
          
          images[a] = image;
          a++;
        }
        
      })
    
     
      }
  })
  

  
  }

This project is to work as an API, I don’t want it to have views, the user will just have an APP in react native making requests to the laravel API