How to get file contents from ipfs-http-client

I am using ipfs-http-client to read the contents of a file form infura, how do i use the “cat” funtionality to correctly get the data in a string/json format?

 const client = create({
    url: ipfsUrl(),
    headers: {
      authorization: ipfsAuthPhrase(),
    },
  });
  const cidformat = "f" + cid.substring(2);
  const cidV0 = new CID(cidformat).toV0().toString();
  const resp = await client.cat(cidV0);
  let content = [];
  for await (const chunk of resp) {
    content = [...content, ...chunk];
  }
  console.log(content.toString());

right now i am just getting a array of binaries on the console log.

419 (unknown status), Registeration API fetch, after adding CSFR – VueJs, Laravel Backend

Have tried different ways of adding CSFR as a HTML DOM element, both in head – meta, as well as inside the form. Tried different headers with my fetch POST request.

New to Vue, so maybe I’m missing something and am considering it’s not a CSFR issue at all. Played around with my backend Laravel config, but have another front-end, a mobile app, as well as Postman API testing – All works. After trying google results I’m perplexed. Any thoughts appreciated.

Error: 419 (unknown status) in console after form submition

Login Component Script

<script lang="ts">
import {useRouter} from "vue-router"
import {reactive} from 'vue';

export default {
  name: "Login",
  setup() {
    const data = reactive({
      name: "",
      email: "",
      password: "",
      password_confirmation: "",
      is_admin: 0,
    });
    const router = useRouter();
    const csfr = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    const submit = async () => {
      await fetch('http://localhost:8000/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          "Accept": "application/json",
          "Access-Control-Allow-Origin": "*",
           'X-CSRF-TOKEN': csfr
          },
        body: JSON.stringify(data)
      });
      await router.push('/Dashboard');
    }
    return {
      data,
      submit
    }
  }
}

Register Component Form HTML

<form class="mt-8 space-y-6" @submit.prevent="submit">
        <input type="hidden" id="_token" value="{{ csrf_token() }}">
        <input type="hidden" name="remember" value="true">
        <div class="rounded-md shadow-sm -space-y-px">
          <div>
            <label for="name" class="sr-only">Username</label>
            <input id="name" name="name" type="text" autocomplete="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Full Name">
          </div>
          <div>
            <label for="email-address" class="sr-only">Email address</label>
            <input id="email-address" name="email" type="email" autocomplete="email" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Email address">
          </div>
          <div>
            <label for="password" class="sr-only">Password Confirmation</label>
            <input id="password" name="password" type="password" autocomplete="current-password" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password">
          </div>
          <div>
            <label for="password_confirmation" class="sr-only">Password</label>
            <input id="password_confirmation" name="password_confirmation" type="password" autocomplete="current-password_confirmation" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password Confirmation">
          </div>
        </div>

Head Meta HTML (Just in case)

<head>
    <meta charset="UTF-8" />
    <meta name="csrf-token" content={{ csrf_token() }} />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>

call function using onclick inside string for loop

I am creating a table depending on the result of a function for then append in a div like this:

    let result = document.getElementById("result");
    consultCities();
    
    function consultCities (){
        consultarAPI(username, password, "cities")
        .then((response) => {
            if(response.login !== "Fail"){
                let table = "";
                let thead = "";
                let tbody = "";
    
                thead += `<tr>
                            <th>Citie</th>
                            <th>Dane</th>
                            <th>Look Institution</th>
                          </tr>`
                for(let i = 0; i < response.data.length;  i += 1 ){
    
                    tbody += `<tr>
                                    <td>${response.data[i].name}</td>
                                    <td>${response.data[i].dane}</td>
                                    <td><button type="button" id="ver" onclick="${consultInstitutions(response.data[i].dane)}">Ver</button></td>
                               </tr>`
                }
    
                table += `<table class="table table-bordered">
                            <thead>
                                ${thead}
                            </thead>
                            <tbody>
                                ${tbody}
                            </tbody>
                          </table>`
    
                result.innerHTML = table;
            }else{
                alert("El Usuario no existe o la opción no existe");
            }
        });
    }

function consultInstitutions(codCity){
    console.log(codCity);
}

The problem is the onclick trigger runs automatically although I don’t click in any button, my question is there a best way that I can set onclick a button for a string?

Webpack – linking other Pug pages on webpack-dev-server doesn’t work

I’m rebuilding my own website and I want to add some transitions between pages.

In this example I have two pug files in my src folder:
In index.pug I have a line of code ( a(href='./about') Go to about ) which should link to the about webpage.
Instead I get this error cannot get /.

If I change that to ( a(href='./about.html Go to about ) and run this in production everything is working smoothly.

My folder structure is:

dist/
  +-- index.html
  +-- about.html
  +-- main.css
  +-- main.bundle.js
  +-- vendor.bundle.js
node_modules/
src/
  +-- partials/
  +-- sass/
  +-- index.pug
  +-- about.pug
  +-- index.js
  +-- vendor.js
  +-- main.scss
.gitignore
package-lock.json
package.json
webpack.common.js
webpack.dev.js
webpack.prod.js

webpack.common.js

const path = require('path');
//const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js'
  },
  //plugins: [
  //  new HtmlWebpackPlugin({
  //    template: './src/index.pug'
  //  })
  //],
  module: {
    rules: [
      {
        test: /.(svg|png|jpe?g|gif)$/i,
        type: 'asset/resource',
        generator: {
         filename: 'images/[hash][ext][query]',
       }
      },
      {
        test: /.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-proposal-object-rest-spread']
          }
        }
      }
    ]
  }
};

webpack.prod.js

const path = require('path');
const common = require('./webpack.common.js');
const { merge } = require('webpack-merge');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require("terser-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = merge(common, {
  mode: 'production',
  output: {
    filename: '[name].[contenthash].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  optimization: {
    minimizer: [
      new TerserPlugin(),
      new HtmlWebpackPlugin({
        template: "./src/index.pug",
        filename: 'index.html',
        minify: {
          removeAttributeQuotes: true,
          collapseWhitespace: true,
          removeComments: true
        }
      }),
      new HtmlWebpackPlugin({
        template: "./src/about.pug",
        filename: 'about.html',
        minify: {
          removeAttributeQuotes: true,
          collapseWhitespace: true,
          removeComments: true
        }
      })
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'
    }),
    new CleanWebpackPlugin()
  ],
  module: {
    rules: [
      {
        test: /.pug$/,
        use: [
          {
            loader: 'simple-pug-loader'
          }
        ]
      },
      {
        test: /.scss$/,
        use: [
          MiniCssExtractPlugin.loader, //3. Creates separate CSS file
          'css-loader', //2. Turns css into js
          'sass-loader' //1. Turns sass into css
        ]
      },
      {
        test: /.(gif|png|jpe?g|svg)$/i,
        use: [
          // Using file-loader will create another set of images and will link to the wrong images
          // As of Webpack 5.0, this can be handled without installing a loader at all. So file-loader, url-loader, raw-loader, etc. are now obsolete.
          // https://stackoverflow.com/questions/69147962/file-loader-creating-2-images-and-linking-the-wrong-one
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
              },
              optipng: {
                enabled: false,
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4
              },
              gifsicle: {
                interlaced: false,
              },
              webp: {
                quality: 75
              }
            }
          }
        ]
      }
    ]
  },
});

webpack.dev.js

const path = require('path');
const common = require('./webpack.common.js');
const { merge } = require('webpack-merge');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = merge(common, {
  mode: 'development',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /.pug$/,
        use: [
          {
            loader: 'simple-pug-loader'
          }
        ]
      },
      {
        test: /.scss$/,
        use: [
          'style-loader', //3. Injects css into the DOM
          'css-loader', //2. Turns css into js
          'sass-loader' //1. Turns sass into css
        ]
      },
    ]
  },
  devServer: {
    hot: true,
    liveReload: true,
    open: 'Google Chrome'
  },
  plugins: [
    new LiveReloadPlugin({  // LiveReloadPlugin is necessary in order to fix live reloading on the dev side
      appendScriptTag: true
    }),
    new HtmlWebpackPlugin({
      template: './src/index.pug'
    }),
    new HtmlWebpackPlugin({
      template: './src/about.pug'
    })
  ]
});

I tried adding a new template in the HtmlWebpackPlugin in webpack.dev.js (this worked in production ), but it only shows the about page in localhost:8080 followed by this error:

Compiled with problems:X
ERROR
Conflict: Multiple assets emit different content to the same filename index.html

SuperHero API – Access Token [closed]

I’m trying to retrieve a json response from SuperHero API but can’t find where to create an access token anywhere.
When trying to test a request on the website it says I need to log in via Facebook but there’s no option to do that.
Is the Api still active?
Anyone has an access token I can use?

Different result from array in html than in console

I am using ajax and jquery to get json from database and everything is great but in console when I log data[i].userID I get all elements which is: 55 57 58 59 but when I display in html code I got only last one, can’t find problem, anyone can help me? Thanks

$(function(){ 
    $("#users").on('click', function(){ 
    document.getElementById('top-today').classList = ('hide-cards');
    document.getElementById('type').innerHTML = "History";
    const fictionCards = document.getElementById('fiction-cards');
    while(fictionCards.children && fictionCards.children.length) {
        fictionCards.removeChild(fictionCards.children[0]);
    }
    $.ajax({ 
      method: "GET", 
      
      url: "connection.php",
      success: function(data) {
          for (i = 0; i< data.length; i++){
              console.log(data[i].userID);

              const string = `
              <table class="table table-striped">
              <thead>
              <tr>
                  <th scope="col">ID</th>
                  <th scope="col">First Name</th>
                  <th scope="col">Last Name</th>
                  <th scope="col">email</th>
              </tr>
              </thead>
              <tbody>
              <tr>
                  <th scope="row">${data[i].userID}</th>
                  <td>${data[i].firstName}</td>
                  <td>${data[i].lastName}</td>
                  <td>${data[i].email}</td>
              </tr>
              </tbody>
              </table>`; 
              $("#fiction-cards").html(string);
          }
      }
    }) 
  }); 
}); 

Uncaught ReferenceError: $ is not defined in console

I am trying to append a div when a checkbox is selected in dajngo template but i keep receiving Uncaught ReferenceError: $ is not defined in the console

the template:

{% extends 'base_layout.html'%}
{%load static%}
{% block content %}
<div class="inventory-content">
    <div class='category'>
        <div>Categories</div>
        <div class='category-checkbox'>
            {%for category in categories%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
            <label for="{{category.name}}"> {{category.name}}</label><br>
            {%endfor%}
        </div>
    </div>
    <div class='items'></div>

</div>    

<script>
    $('.category-checkbox input[type="checkbox"]').click(function (){
        if ($(this).is(':checked')) {
             // Add the element to the div with an id identifier
             $('.items').append('<div id="[{{category.id}}]">123</div>');
        } else {
             // Remove the element from the div targeted by the id identifier
             $('.items #[{{category.id}}]').remove();
        }
    });
</script>
{% endblock %}

How do I implement Lodash ._chain function?

I’m trying to remove lodash from my project, and one of the functions we use is the ._chain. It is being used like so:

chain(sortedItems || allItems)
            .filter((x) => this.filterItemsBySearchParam<T>(x, search))
            .filter((x) => this.filterItemsByFacets<T>(x, facets))
            .groupBy((x) => (groupBy ? [groupBy.split(',').map((path) => get(x, path))] : ''))
            .map((filteredItems: any, key) => {
            ...

I tried this, but couldn’t get it to work:

private chain(value) {
    return {
        /**
       * @param {function|string} func function or function name (in chained value)
       * @param  {...any} args
       */
        filter(func, ...args) {
            if (typeof func === 'string') {
                return chain(value[func](...args));
            }
            return chain(func(value, ...args));
        },
        value: () => value,
    };
}

Is there a better way to achieve this?

Array of objects convert to object with keys by item field value

I have this array:

const demo = [
  { key: 'apple', a: 'b', c: 1 },
  { key: 'banana', a: 'f', c: 3 },
  { key: 'orange', a: 'j', c: 8 },
];

I can get info about “banana” by using:

demo.find(item => item.key === 'banana')

Instead I would like to have this associative and access like this:

demo.banana.c

So I need to somehow get this:

const demo = {
  'apple': { key: 'apple', a: 'b', c: 1 },
  'banana': { key: 'banana', a: 'f', c: 3 },
  'orange': { key: 'orange', a: 'j', c: 8 },
};

Or without “key” inside, it does not matter.

What would be simplest solution? Some simple (maybe one-line) approach with ES6? If not, Lodash instead?

initial configuration error react router dom v6

I’m trying to configure the react router dom route structure, but apparently my routes are not being recognized within the application

routes/index.tsx

import React from 'react';
import { inject, observer } from 'mobx-react';
import { Routes, Route, Link } from "react-router-dom";
import {
  Main,
} from '../scenes';
import { Routes as RoutesPath } from './routing';

const RoutesContainer: React.FC = () => (
  <Routes>
    <Route path={RoutesPath.MAIN} element={<Main />} />
  </Routes>
);

export { Routes };
export default inject('routing')(observer(RoutesContainer));

index.tsx (aplication)

import React from 'react'
import { Provider } from 'mobx-react';
import { render } from 'react-dom'
import './index.css'
import store from './stores';
import { Routes } from './routes';
import { BrowserRouter } from 'react-router-dom';

render(
  <Provider rootStore={store}>
    <BrowserRouter>
      <React.StrictMode>
        <Routes />
      </React.StrictMode>
    </BrowserRouter>
  </Provider>,

  document.getElementById('root')
)

If I remove my component, and add some text it displays correctly, but with the component it displays a blank screen.

‘,’ at error in visual studio code.This is the code

import React, { Component } from 'react';
import { MenuItems } from './MenuItems';

class Navbar extends Component {
    render() {
        return (
            <nav class-name="NavbarItems">
                <h1 class-name="navbar-logo">React<i className="fab fa-react"></i></h1>
                <div class-name="menu-icon">


                </div>
                <ul>
                    {MenuItems.map((item, index) => {
                        return( <li key={index}>
                            <a class-name={item.cName} href={item.url}>
                                {item.title}
                            </a>
                        </li>)}}
                </ul>

            </nav>
        )
    }

}

export default Navbar

Is it possible to block xhr/fetch from an iframe that has scripting allowed

I have a sandbox iframe that I’m running untrusted third-party user code in and I’m sending data from the parent page into the iframe. To prevent phishing problems in the event that the end-user is tricked into entering valuable creds into the iframe, is there a way to prevent the iframe from exfiltrating that payload by preventing requests from going out from the iframe?

FullCalendar is sending the server an odd start and end value to fetch the events

I am trying use the FullCalendar v5 plugin to add a calendar on my website. I want to fetch the events using AJAX request.

Here is what I have done

let calendarElement = document.getElementById('calendarElement');

let calendar = new FullCalendar.Calendar(calendarElement, {
            initialView: 'dayGridMonth',
            aspectRatio: 2.0,
            headerToolbar: {
                left: 'prev,next',
                center: 'title',
                end: 'dayGridMonth,timeGridWeek,listWeek, today prev,next'
            },
            weekNumbers: false,
            lazyFetching: false,
            events: {
                url: '/events',
                method: 'GET',
                startParam: 'start', // I expect this to always be the begin of the month
                endParam: 'end', // I expect this to always be the end of the month
                failure: function (e) {
                    console.log(e);
                }
            }
        });

calendar.render();

However, then the values sent to the server seems to have the wrong start/end values. /events?start=StartValue&end=EndValue

If I am looking at events for the month of February, I expect the plugin to sent a GET request to the server with 2/1/2022 00:00:00 value for the start and `2/28/2022 23:59:59′ for the end date.

However, the plugin seems to be sending odd range to the server. The plugin send the value 1/30/2022 5:00:00 AM as start value and 3/13/2022 5:00:00 AM as end value. My PC time zone is -5 from UTC which explains the 5 hours. But I would expect the end value to be 2/28/2022 not 3/13/2022

How can I fix this issue so that the plugin send the exact range based on the user’s view?