axios: how to access response when getting 403 exception?

I have the following scenario:

The backend detects that the token has expired, so it returns 403 with custom “error” response header.

This can be reproduced by firing the following request:

axios.get(MY_URL)
     .then(res => console.log("I am expecting to enter this block, and do something with the response header"))
     .catch(err => console.log("But instead I skip the Then block and go straight here...));

In Chrome’s networking tab, I can indeed see that the header is there in the response:

<Response headers>
content-type: application/json
error: JWT expired at ......... <-- my header

However, it appears that I go straight into the catch block, where I do not have an access to the response and its headers. I was expecting to go into the then block and do some logic, such as:

.then(res => {
  if (res.statusCode === 403 && res.headers['error'] === 'JWT expired at .....') {
    // refresh token...
  }
});

How can I access my response and its headers, when the then block is skipped?

How to get arguments of another function? [duplicate]

I am trying to make a Express.js package that automatically generates routes from a object.

For example, if I were to put this in,

  info: {
    name: "Test",
    version: "V1.0.0",
    config: {
      platform: "express.js"
    }
  },
  users: {
    add: async function(firstName,lastName,email) {
      return email
    }
  }
}

then example.com/info/version would return V1.0.0.

That part I have already created successfully, but now I want to do the same for functions. I figure that I can pull arguments from query strings or bodies of POST requests and match them up with function arguments.

So now I need to find a way to get a function’s arguments, more specifically the argument names.

What I mean is that for the users.add function, I’d ideally like a array of arguments like ['firstName','lastName','email'] to be returned automatically.

Javascript : Parameters in a parent function are undefined in child function

I’ve been searching for hours and still dont understand what’s the problem with my code. I’ve got a main function called “req” and in this function there’s another arrow function called “data”. When I try to access the “author” and “collection” parameters of the main function, I get a Reference Error : the variables are undefined. Thanks for your help !

const puppeteer = require('puppeteer');
const fs = require('fs');

function saveData (jsonData) {
    fs.writeFile("myData.txt", jsonData, function(err) {
        if (err) {
            console.log(err);
        }
    });
}

async function req (author, collection) { // The two parameters are here : author and collection
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    let link = 'www.myexampleurl/'+ author + '/'+ book + '/';
    await page.goto(link);
    const data = await page.evaluate(() => { // Here's the arrow function
        let elements = document.querySelectorAll('span.alldetails');
        let myBooks = [];
        for(element of elements) {
            myBooks.push(
                {   
                    authorName : author, // !!!!! UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: author is not defined
                    collectionName : collection, // !!!!! UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: collection is not defined
                    description : element.description
                }
                )
            }
            return myBooks;
        });
        saveData(JSON.stringify(data)); // A simple function that works to save the data in a text file
        browser.close();
            
};

req('john_doe', 'the_best_jd_books');

Function class javascript not finding variable

I have two javascript docs on my project.
js (script.js) #1:

let func = new Function('return thisvar')
console.log(func())

js (script1.js) #2:

let thisvar = 'hello'

I get an error:
ERROR:{@script.js line 4: cannot find variable 'thisvar'}
I have tried using var instead of let or even window.thisvar
What am I doing wrong?

Generate image from node array [duplicate]

I’m trying to generate an image with the given array of ints, where 1 is white and 0 is black.

var intArray = [
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]; 

Here is what I’ve tried:

function saveImage(filename, data){
  var buffer = new Buffer(data.length);
  for (var i = 0; i < data.length; i++) {
    buffer[i] = data[i];
  }

  fs.writeFile(filename, buffer, function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log("saved");
    }
  });
}

saveImage("image.jpg", intArray);

But the image file that is created is not a valid jpeg and I cannot view it, what am I doing wrong?

How to filter out dragged and dropped items properly in React JS?

I am learning React. I am trying to work out a drag and drop functionality from scratch. I am almost done but when I move an item from one div and try to move back to the original div, its throwing an error. If you are suggesting to use react-dnd, I already tried but I am not able to find a simple example, where I can just try the functionality. Here is what I tried.

Link: https://codesandbox.io/embed/fancy-surf-gnjpv?fontsize=14&hidenavigation=1&theme=dark.

Thanks in Advance

Axios.get() request returning undefined

In the below code Iam trying to use axios get request from await axios.get('/products/api')
is only working i can see the data in the console but forawait axios.get('/users/api')Undefined is being returned on the console but when i try get request through Postman i can get the results .Iam stuck here.

”’ const [userdata, setuserdata] = useState([]);
const [products, setproducts] = useState([]);

useEffect(() => {
    const fetchUserData = async () => {
        
        const { users } = await axios.get('/users/api')
        setuserdata(users);

        const { data } = await axios.get('/products/api')
        setproducts(data);
    }
    fetchUserData();



}, []);
console.log(products)
console.log(userdata)

hover style on page load

I’m looking for a simple way to persist a “hover” style on a page refresh if the user did not move his mouse. The issue is that the hover style is only triggered on a mouse enter/mouseover event, so on a page refresh it will not be applied even if the cursor is above the item in question until the user touches the mouse again and moves it slightly. The code below has this issue.

$('div').click(function () {
     window.location.reload();
});
div {
   width: 100px;
   height: 100px;
   background: grey;
}
div:hover {
   background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>

Immutable date, datetime and timedelta library for react native

Coming from python I am having a very hard time adapting to the way dates and datetimes are handled in javascript/typescript.

I’d rather not use moment.js as it is considered legacy and I’d really like to have immutable objects.

Luxon is not a good choice for me either because it means I have to eject from expo go. I do not have a mac so I have to use my wifes iPhone, which means I am stuck to this app.

date-fn requires me to set the locale manually on every localization request.

In short I would like to have a javascript library that can localize immutable datetime objects out of the box, has support for timedeltas (or intervals, or durations) and if possible has support for non-localized time objects.

I don’t believe this is an uncommon problem and yet those are the only 3 libraries I keep finding.

How to handle 3 different conditions in a React functional component

I am rendering out a lists of posts. There are 3 different types of content these posts will show. So the list view of all of these posts is the same. Standard title, thumbnail, author, etc. But when you go to the page of these 3 different types the content renders a different layout (different component). I have a simple ternary operator to set the different links for 2 of the link types. But now that I have 3 what is the best practice to setup that logic?

Here is what I have so far:

 <div className="all-posts">
                    { currentPosts?.map(post => (
                        <Link key={post.id} className="link-wrapper" to={post.course_trailer ? `course/${post.id}` : `/lesson/${post.id}`}> 
                            <div  className="post-container">
                                <div className="thumbnail-container">
                                 <img className="post-thumbnail" src={post.course_trailer ? post.featured_image : post.app_thumbnail} alt="" />
                                </div>
                                <div className="post-meta">
                                    <p className="post-title">{post.title}</p>
                                    <div className="author-meta">
                                        <div className="author-container">
                                            <p className="post-teacher">@{post.instructor_name}</p>
                                            <img className="verification-badge" src="#" alt="" />
                                        </div>
                                        <p className="post-views">Views: {post.views}</p>
                                    </div>
                                </div>
                            </div>           
                        </Link>
                    ))
                    }  
    </div>

You see in the Link I have the ternary. Now I need to setup the logic like if post.course_trailer go to this path if post.formulas then go to this path else go to the standard path.

Iterate over table using puppeteer

I want to get data from a website which is in table. First i try to get the whole table and then get the tr‘s and td‘s that are inside it. The code i have now just return empty array.

const puppeteer = require("puppeteer");

async function run() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto(
    "https://www.basketball-reference.com/leagues/NBA_2021_standings.html" //Eastern Conference
  );

  var temp = [];
  const data = await page.evaluate(() => {
    const tableBody = document.querySelector(
      'table[id="confs_standings_E"] tbody'
    );

     for (var i = 0; i < tableBody.length; i++) {
      const tr = tableBody[i].querySelectorAll("tr");
      for (var j = 0; j < tr.length; j++) {
       const td = tr[j].querySelectorAll("td").innerText;
       temp.push(td);
  }
}
  });

  console.log(temp);
  //await browser.close();
}

run();

Thanks for any help

Invalid hook call. How to set a value with react axios get call?

I have this react component that has a simple form where, when you put a superhero name, it makes an axios get request to an API that responds successfully with json object with info of said hero. That info is stored in the state and then mapped through to create a grid. It used to work just fine as a class element so I started doing other parts of the app that have nothing to do with this part, but when i run the whole app again so check i get an hook call error in this component.

This is the seeker component, i did the class and the funcion version.

import React, { useState } from "react";
import { Formik, Form, Field, ErrorMessage } from 'formik';
import axios from "axios";
require("babel-core/register");
require("babel-polyfill");
import grid from "../components/grid";


/* 
const Seeker = () => {
   const fetchData = (data) => {axios.get(`https://www.superheroapi.com/api.php/1589015884770221/search/${name}`)
       .then((response) => {
           localStorage.setItem("addHeroAction", true);
           let results = response.data.results;
           localStorage.setItem("matchedHeros", results);
       }).catch((error) => {
           console.log(error)
       })
   }

   let matchedHeros = localStorage.getItem("matchedHeros") ? localStorage.getItem("matchedHeros") : [];
   
   const gridRender = (response) =>{
       if(response.length && response != undefined){
           console.log(response)
           return( 
           <div className="grid__background">
           <div className="grid">
               <div className="grid__box grid__top grid__top--container"></div>
               <div className="grid__box grid__top grid__top--container"><h2>Name</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Intelligence</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Strenght</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Speed</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Durability</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Power</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Combat</h2></div>
               <div className="grid__box grid__top grid__top--container"></div>
               {response.map(hero => grid(hero, hero.id))}
           </div>
           </div>)
       } else {
           return (<div></div>)
       }
   }

   return (
       <div>
           <h1>Find your next teammate!</h1>
               <Formik
               initialValues={{ name: ''}}
               validate={values => {
                   const errors = {};
                   if (!values.name) {
                       errors.name = 'Required';
                   } else if (
                       !/^[a-zA-Z]*$/.test(values.name)
                   ) {
                       errors.name = 'Invalid name';
                   }
                   return errors;
               }}
               onSubmit={(values) => {
                   console.log(fetchData(values.name));
               }}
               >
               {() => (
                   <Form>
                   <Field type="text" name="name" />
                   <ErrorMessage name="name" component="div" />
                   <button type="submit">
                       Submit
                   </button>
                   </Form>
               )}
               </Formik>
                   {gridRender(matchedHeros)}
       </div>
       )
   } */


   class Seeker extends React.Component{
   state = {
       matchedHeros : [],
       loadingData : true
   }
   constructor(){
       super();
       this.fetchData = this.fetchData.bind(this);
   }

   
   fetchData = async (name) => {
       if(this.state.loadingData){
           await axios.get(`https://www.superheroapi.com/api.php/1589015884770221/search/${name}`)
           .then((response) => {
               localStorage.setItem("addHeroAction", true);
               this.setState({matchedHeros : response.data.results, loadingData : false});
           }).catch((error) => {
               console.log(error)
           })
       }
  
       
   }     

   
   render(){
       return (
           <div>
               <h1>Find your next teammate!</h1>
                   <Formik
                   initialValues={{ name: ''}}
                   validate={values => {
                       const errors = {};
                       if (!values.name) {
                           errors.name = 'Required';
                       } else if (
                           !/^[a-zA-Z]*$/.test(values.name)
                       ) {
                           errors.name = 'Invalid name';
                       }
                       return errors;
                   }}
                   onSubmit={(values) => {
                       this.fetchData(values.name);
                   }}
                   >
                   {() => (
                       <Form>
                       <Field type="text" name="name" />
                       <ErrorMessage name="name" component="div" />
                       <button type="submit">
                           Submit
                       </button>
                       </Form>
                   )}
                   </Formik>
                   {console.log(this.state.matchedHeros)}
                   {this.state.matchedHeros.length ?  
                       (
                       <div className="grid__background">
                           <div className="grid">
                               <div className="grid__box grid__top grid__top--container"></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Name</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Intelligence</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Strenght</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Speed</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Durability</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Power</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Combat</h2></div>
                               <div className="grid__box grid__top grid__top--container"></div>
                           </div>
                       </div>
                       )
                       :
                       <div></div>
                   }
                   {this.state.matchedHeros.map(hero => grid(hero, hero.id))}
           </div>
           )
   }
} 


export default Seeker; 

It uses the formik library to verified the values and the it maps the info with a Grid component that works just fine on its own, so the problem is in this component. The axios call also sets a value in localStorage that i need to be set when the button is clicked.

The original was the class component but with it I have this error on the console.

“Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.”

Then i made the functional component version, which is commented in the code above, but with it i can’t get the state updated with axios.

When i look into someone else’s examples they look like mine but I still get the hook call error, i already checked that i have up-to-date versions of react so that’s not the problem.
What am I doing wrong? or else, what suggestion can you guys give me to achieve the same result?

Global event listener with DataTables

As you can see below, I have an event listener within the processServiceConsumers function. How can I have it outside the functions so it’s a global event listener?

function getServiceConsumers() {
    
    return $.ajax({
        url: baseURL + "serviceConsumers?connectionPointId=" + ntjpProdConnectionPointId,
        success: function(result){
            processServiceConsumers(result);
        }
    });
    
}

function processServiceConsumers(data) {
    
    $("#serviceConsumersWrapper").show();
    
    var serviceConsumersTable = $('#serviceConsumersTable').DataTable( {
        data: data,
        dataSrc: "",
        columns: [
                { data: "id", orderData: 2 },
                { data: "hsaId" },
                { data: "description" }
            ],
        select: true
    } );
    
    serviceConsumersTable.on( 'select', function () {

        var selectedRowId = serviceConsumersTable.rows( { selected: true } ).data()[0].id;
 
        // getServiceContracts(selectedRowId);
        
    } );

}

Is there a property like word-wrap or overflow-wrap that can force breaks at word boundaries?

For example, If I have a sentence like the following:

I like cute dogs because they’re awesome

doing something like word-break: break-word might give you

I like cute dogs because they’re awe

some

The behavior I want is for it to break like

I like cute dogs because they’re

awesome

I can’t seem to find a way to do this. In most cases, the words do seem to fit efficiently into the container, but there are weird cases with long words that spill out even though I would think it should know how to rearrange them for this not to happen. The words aren’t even close in length to the width of the container, so it’s not that what I’m trying to achieve is impossible or anything. The CSS I have written is so negligible that it’s probably not even worth including, but it’s something like:

.someClass {
   margin-bottom: 2rem;
   padding: 0.5rem;i 
}

p {
   font-size: 1.1rem;
   margin-bottom: 0.375rem;
}

.someClass’s size is a fixed value, and its parent is a flex container. I tried adjusting the available space of the flex cell it occupies to exactly the size of the contained element but it made no difference.

  1. Why do words which are only a fraction of the width of the parent overflow sometimes? Like, why aren’t they auto arranged to divide the space without overflowing?
  2. Is there a way to ensure no overflow but without breaking mid-word, and instead breaking at word boundaries

Thanks for the help and cheers.

Library – adding books – HTM, CSS, JavaScript

I didn’t find a reply so I’m creating a new post. I’m a newbie into JS and I’d like to create a kind of library.
Explanation:
We have a form with input “user” and “author” and “category”
Button – to submit form.
I’d like to display data from my form under it (like on the attached screenshot).

My problem is that I don’t especially know how to display new data from the form (please take a look at code). I’m certainly sure that I should kind of a loop to create and display new UL with nested LI but I don’t know how :/.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
        <label for="title"></label>
        <input type="text" name="title" id="title">
        <label for="author"></label>
        <input type="text" name="author" id="author">
        <label for="category"></label>
        <select name="category" id="category">
            <option value="fantasy">Fantasy</option>
            <option value="sci-fi">Sci-Fi</option>
            <option value="romans">Romans</option>
        </select>
        <button type="submit" id="submit">Zatwierdź</button>
    </form>
    
    <script src="script.js"></script>
</body>
</html>
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');

let books = [];

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);

    let elementUl = document.createElement('ul');

    function addElement() {
        
        let elementTitle = document.createElement('li');
        let elementAuthor = document.createElement('li');
        let elementCategory = document.createElement('li');
    
        let titleContent = document.createTextNode("Title: " + books[0].title);
        let authorContent = document.createTextNode("Author: " + books[0].author);
        let categoryContent = document.createTextNode("Category: " + books[0].category);
           
        elementTitle.appendChild(titleContent);
        elementAuthor.appendChild(authorContent);
        elementCategory.appendChild(categoryContent);
    
        elementUl.appendChild(elementTitle);
        elementUl.appendChild(elementAuthor);
        elementUl.appendChild(elementCategory);
    
        document.querySelector('body').appendChild(elementUl);
    }  

    addElement();
      
}

btn.addEventListener('click',submitForm);