by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
  • Dec 21 2018 17:11
    @MadLittleMods banned @OmarAlmaqtri
  • Jun 05 2018 23:13
    @MadLittleMods banned @LWSS
  • May 25 2018 16:50
    @MadLittleMods banned @TheRedstoneTaco
Julian Gonggrijp
@jgonggrijp
@rohyadav :point_up: 13 juli 2020 06:57
What exactly are you trying to do? The snippet that you showed will iterate all keys but it will output only the last. Also, you're checking that the field isn't null or undefined, but I don't think Object.keys ever produces such values.
Haneen Jaber
@haneenJabr

Hello,

I'm a java developer and I need to do something in javascript, I have a task to use service worker in order to renew access token when token has been expired

I'm stuck with retrying the request after getting a new token from authorization server, I get an error that I can't clone or alter the headers of the request

Here is my service worker code:

sw.js

self.addEventListener('install', function(event) {
    console.log("install");
});

self.addEventListener('fetch', function(event) {
    console.log('fetching ->', event.request);
    event.respondWith(
        fetch(event.request)
        .then((resp) =>{
             if(!resp.ok && self.getAuthHeaderDetails(resp.headers) =="invalid_token"){
               console.log(" token is revoked or expired trying to fetch a new access token");
               self.renewedToken("http://localhost:8080/auth/realms/Myrealm/protocol/openid-connect/token");
               customHeaderRequestFetch(event);
              }
            return resp;
        })
        .catch((err) =>{
            console.log("something went wrong: ", err);
        })
    );
});


function customHeaderRequestFetch(event) {
  var newRequest= event.request.clone();
  newRequest.header('x-my-custom-header','The Most Amazing Header Ever');
  }



self.addEventListener('message', function(event) {
    console.log(`Received a message from main thread: ${event.data}`);
    event.ports[0].postMessage(`Roger that! - "${event.data}"`);
});


function renewedToken(url){

          let formData = new FormData();
          formData.append('grant_type', 'refresh_token');
          formData.append('refresh_token', 'John123');
          formData.append('client_id','JFW-GWT');
          const dataf = new URLSearchParams(formData);
          fetch(url, {
          method: 'post',
          body: dataf,
          headers: {
             'Content-Type': 'application/x-www-form-urlencoded',
             'Sec-Fetch-Dest': 'empty',
             },
             })
            .then( res => res.json() )
            .then( data => console.log(data) );
 }


function getAuthHeaderDetails(headers){
           if(headers.get("WWW-Authenticate") !== null){
               console.log("not OK", headers.get("WWW-Authenticate"))

                var x= headers.get("WWW-Authenticate")
                var y = x.replace(/\"/g, "");
                const table =
                 y.split(", ") //["key:value","key:value"]
                  .map(pair => pair.split("=")); //[["key","value"],["key","value"]]

                console.log(table);

                const result = {};
                table.forEach(([key,value]) => result[key] = value);

                console.log( result.error );

                return result.error;
             }
                return "";
}

script.js

if (navigator.serviceWorker) {
    console.log("ServiceWorkersSupported");

    navigator.serviceWorker.register('sw.js', {
        scope: './'
    })
        .then(function(reg) {
            console.log("Service Worker started", reg);
        })
        .catch(function(error) {
            console.log("Failed register ServiceWorker", error);
        });
}

var log = console.log.bind(console);
var error = console.error.bind(console);

if (navigator.serviceWorker) {
sendMessage('hello').then(log, error).catch(error);
}

function sendMessage(message) {
    return new Promise((resolve, reject) => {
        const messageChannel = new MessageChannel();
        messageChannel.port1.onmessage = function(event) {
            resolve(`Received a direct message from the ServiceWorker: ${event.data}`);
        };
        navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2])
    });
}

I called script.js inside my index.html page

Sidharth-Bansal
@Sidharth-Bansal
hi
const express = require("express");
const session = require("express-session");
const redis = require("redis");
const redisStore = require("connect-redis")(session);
const client = redis.createClient();
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const TWO_MINUTE = 1000 * 60 * 2;
const {
  NODE_ENVIRONMENT = "development",
  SESSION_NAME = "SID",
  HOST = "localhost",
  PORT = 6379,
  TTL = 260,
  SESSION_SECRET = "gamezySecretsNeverRevealed",
  SESSION_LIFETIME = TWO_MINUTE,
} = process.env;
const IN_PROD = NODE_ENVIRONMENT === "production";
app.use(
  session({
    name: SESSION_NAME,
    store: new redisStore({
      host: HOST,
      port: PORT,
      client: client,
      ttl: TTL,
    }),
    secret: SESSION_SECRET,
    saveUninitialized: false,
    resave: false,
    cookie: {
      maxAge: SESSION_LIFETIME,
      sameSite: true,
      secure: IN_PROD,
    },
  })
);
const homeRoutes = require("./api/routes/home");
const authenticationRoutes = require("./api/routes/authentication");

// Logger
app.use(morgan("dev"));

// Parsing the incoming data
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Routes which handle requests
app.use("/login", authenticationRoutes);
app.use("/signup", authenticationRoutes);
app.use("/home", homeRoutes);
module.exports = app;
this is app.js
const express = require("express");
const router = express.Router();
const fetch = require("node-fetch");
const app = require("../../app");
var url = "http://192.168.43.106:9090/" + ?;
var headers = {
  "Content-Type": "application/json"
};
const redirectHome = (req, res, next) => {
  if (req.session.username) {
    res.status(302).send("Home");
  } else {
    next();
  }
};
router.post("/", redirectHome, (req, res, next) => {
  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      username: req.body.username,
      password: req.body.password,
    }),
  })
    .then((response) => {
      res.status(response.status);
      if (response.status === 200) {
        req.session.username = req.body.username;
      }
      return response.text();
    })
    .then((text) => {
      res.json(text);
    })
    .catch((error) => {
      console.log("-----error----");
      console.log(error);
      console.log("-----error----");
      next(error);
    });
});

module.exports = router;
this is the authentication.js
can anyone tell me how to use /login supplied or /signup supplied from the first file to the second
Julian Gonggrijp
@jgonggrijp
:point_up: 15 juli 2020 10:44
Hi @haneenJabr :wave:
Such large amounts of code are a bit difficult to read here inside Gitter. Could you put your code in a gist or a jsFiddle? Also, could you identify the line that is throwing the error?
@Sidharth-Bansal It's basically the same story with your question, except that you haven't mentioned yet which errors or other problems you're running into.
Haneen Jaber
@haneenJabr

@jgonggrijp here you go: https://gist.github.com/haneenJabr/a18941cd6ef0cd3d11b18031b151c621

Line number 13 in sw.js file which throw the error that I can't clone or alter the headers of the request inside a fetch

Julian Gonggrijp
@jgonggrijp

@haneenJabr That line is just a call to customHeaderRequestFetch on lines 24-27, so I figured that the actual problem is probably in the newRequest.header call on line 26. I read here that

If intend to modify the request, you may prefer the Request constructor.

which seems to indicate that you shouldn't try to modify a request that you created with the clone method. So maybe change the customHeaderRequestFetch function into this:

function customHeaderRequestFetch(event) {
    var newRequest = new Request(event.request, {
        headers: {
            'x-my-custom-header': 'The Most Amazing Header Ever'
        }
    });
}

It's just a guess though. To be honest, I never worked with service workers nor the fetch API myself.

5 replies
meladon1337
@meladon1337
can someone tell me what i ahve to do to get this running?

i have

<script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>

but it seems not to work

Julian Gonggrijp
@jgonggrijp

@meladon1337 The "Getting started" section at the top of the README states:

In order to make your content be loaded by LazyLoad, you must use some data- attributes instead of the actual attributes. Examples below.

Did you follow those instructions?

kristjan-brezovnik
@kristjan-brezovnik
Hi!
Does Hanami javascript helper support JS modules? If so, how can I specify that a JS file is a module?
Julian Gonggrijp
@jgonggrijp
@kristjan-brezovnik I don't know, but I suggest copy-pasting your question into your favorite web search engine. I suspect that might produce good answers.
kristjan-brezovnik
@kristjan-brezovnik
@jgonggrijp I did, but I didn't get anything useful. I also checked https://guides.hanamirb.org/helpers/assets/ and I tried to call it separately with a param (like the example of async), but it didn't work either.
Julian Gonggrijp
@jgonggrijp
@kristjan-brezovnik Sorry to hear that documentation about JS modules in Hanami is so hard to find. Most of the time when relatively new features aren't documented, it means they aren't supported, so that might be your safest bet.
Maybe you can still write your code in ESM syntax and then transpile it to AMD or bundle it with Rollup?
I don't know what Hanami is so I'm guessing a bit.
Ah, a Ruby web framework. That should give you at least some flexibility.
kristjan-brezovnik
@kristjan-brezovnik
@jgonggrijp My bad for posting in the wrong chat, lol! I just realized that. But thanks for trying to help anyway.:D
lunify
@lunify
Hello guys.
Is there a way to force an object to have a certain shape in JS? I'm looking for the same result that implementing interfacesachieve but for modules/factories
Julian Gonggrijp
@jgonggrijp
@lunify Could you clarify what you mean by "shape" and interfaces?
lunify
@lunify

@jgonggrijp My apologies, the wording was vague at best.
Basically, I'm looking for the equivalent to class X implements I. In other words, a way to ensure a module/factory makes objects that have certain functions implemented.

AFAIK, the direct equivalent is only available via typescript+classes atm, but classes have some other problems, like private fields/methods being only stage-3 for quite some time (and private methods not implemented by babel yet)

Julian Gonggrijp
@jgonggrijp
@lunify What do you mean by "ensure"?
ezekel
@ezekel
Hi guys need some help I have json data and I stored it in select option data-attribute , but I have problme in retrieving on it because I get alwasy [Object,Object]
Stephen James
@sjames1958gm
@ezekel Looks like you are trying log an object? Try JSON.stringify(obj) to see what the value is.
ezekel
@ezekel
Thank you I will try , then how would I retrreive it ? JSON.parse($('#myselect option:selected').attr('data-myjson')); ?
@sjames1958gm
Stephen James
@sjames1958gm
If you are using jquery - https://api.jquery.com/data/
e.g. $( "body" ).data( "foo" );
Idris Fagbemi
@stwins60
Hello
Julian Gonggrijp
@jgonggrijp
Hi @stwins60 :wave:
ezekel
@ezekel
HI is this how we can set value input textfield which is in the last tr ?
$('#expensetable tr:last :input:first').attr('value', 'hello');
but it did not work on me, please help me
`
$('#expensetable tr:last input:first-child').attr('value', 'hello');
Julian Gonggrijp
@jgonggrijp
@ezekel use .val('hello').
Rajat
@rajataudichya
Guys, I need help with FCC recursion challenge
The last one
ezekel
@ezekel
Hi I need some help please , I'm using bootstrap switch, my problem is that if I click the switch and there is error I want not to change, but my problem is it will continue to change or toggle
    $("input[data-bootstrap-switch]").on('switchChange.bootstrapSwitch', function (event, state) {
                if (roleid == null) {
                    swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Role id is missing!'
                    });
                    event.preventDefault();
                    $(this).bootstrapSwitch('state', !state, true);
                }else{
                   //ajax call here
                }

            });
can someone help me please
Julian Gonggrijp
@jgonggrijp
Wrote a tutorial on functional programming, algorithm analysis and design tradeoffs on Stack Overflow, in a question about Underscore. https://stackoverflow.com/a/63088916
jhdurrett
@jhdurrett
Can anyone help me with a form? I was trying to add a honeypot field into my form and now it's not working. I'm very very new to coding and the form is for our website. Any help will be greatly appreciated!! I think when I added/removed the field I must have deleted or even added something to the code that is now causing the form to not submit.
Julian Gonggrijp
@jgonggrijp
@jhdurrett :point_up: 29 juli 2020 01:41
Samuel Fils
@smfils1
Hey guys, I've been working on this fullstack clone for sometime now. Please check it out. https://github.com/smfils1/youtube-clone