Finding the longest connection of ports (JS)

I can’t solve a problem.
We have an array. If we take a value, the index of it means port ID, and the value itself means the other port ID it is connected to. Need to find the start index of the longest sequential connection to element which value is -1.

I made a graphic explanation to describe the case for the array [2, 2, 1, 5, 3, -1, 4, 5, 2, 3]. On image the longest connection is purple (3 segments).

graphic description

I need to make a solution by a function getResult(connections) with a single argument. I don’t know how to do it, so i decided to return another function with several arguments which allows me to make a recursive solution.

function getResult(connections) {
  return f(connections.findIndex(e => e == -1), connections, 0, []);
}

function f(index, cnx, counter, branches) {
  counter++;  
  for (let i = 0; i < cnx.length; i++) {
    if (cnx[i] === index) {
      branches.push([i, counter]);
      return f(i, cnx, counter, branches);
    }
  }
  return branches.sort((a, b) => b[1] - a[1])[0][0];
}

console.log(getResult([1, 2, -1])); // expected 0
console.log(getResult([1, -1, 1, 2])); // expected 3
console.log(getResult([2, 1, -1])); // expected 0
console.log(getResult([3, 4, 1, -1, 3])); // expected 2
console.log(getResult([1, 0, -1, 2])); // expected 3
console.log(getResult([3, 2, 1, -1])); // expected 0
console.log(getResult([2, 2, 1, 5, 3, -1, 4, 5, 2, 3])); // expected 6

Anyway, the code doesn’t work completely properly.
Would you please explain my mistakes?
Is it possible to solve the problem by a function with just one original argument?

get the static part of a RegExp

I want to get the static part of a RegExp string, which 100% guaranteed to not have a regex-specific characters, except the grouping parentheses ().

for instance, this regex /path/config-(.+)/.js/ has a static part /path/config- until the character ‘.’

use cases:

I want to search for all matched entries inside a folder that have too many files and subfolders.

so, it is a bit faster to start searching from the basic path /path that doesn’t needed to be matched against, instead of starting from the root directory.

Read and edit local xml-file in Javascript

I have a directory that contains

--index.html
--script.js
--file.xml

and I want to read the content of the file.xml as a string in order to replace a few words within the xml-file. (Later on I would like to send the edited xml-file as e-mail).

I managed to access to xml-file, but did not manage to save the whole content in a string and/or replace some known keywords within the xml.

This is where I got so far:

var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

function reportStatus2() {
  if (oXHR.readyState == 4)               // REQUEST COMPLETED.
     console.log(this.responseXML)        // This gets me the XML-document, but I want the complete xml content as string
}
oXHR.onreadystatechange = reportStatus2;    
oXHR.open("GET", "../file.xml", true);
oXHR.send();

I found so many posts on that topic here, but none was able to answer my question!
Any ideas?

Create a student timetable using React JS

I’m looking to develop a Timetable for students using React JS to manage their classes online, as you see in some timetable apps in Google Play & App Store. Still, my problem is finding the package to create this timetable.

I couldn’t find any timetable package to use in my app. Can someone please help and suggest a timetable for students?

React Router V6: same Component rendering in multiple routes not updating

This is my App.js:

<Provider store={store}>
        <Header />
        <Routes>
          { categories.map(({ category }) => {
            return (
              <Route 
                key={name}
                exact path={`/${category}`}
                element={<Category name={name} />}
              />
            )
          }) }
        </Routes>
      </Provider>

Category.jsx:

export class Category extends Component {
  render() {
    const { name } = this.props;
    return (
      <div>
        <h1>{name}</h1>
        <CategoryBody name={name} />
      </div>
    );
  }
}

export default Category;

CategoryBody.jsx:

export default class CategoryBody extends Component {
  constructor() {
    super();
    this.state = {
      products: [],
    };
  }

  componentDidMount() {
    const path = window.location.pathname;
    const selectedCategory = path === "/" ? "all" : path.split("/")[1];

    client
      .query({
        query: PRODUCTS_QUERY,
        variables: { title: `${selectedCategory}` },
      })
      .then((result) =>
        this.setState({ products: result.data.category.products })
      );
  }

  render() {
    const { products } = this.state;
    return (
      <div className="category-container">
        {products.map(({ id, name, inStock, gallery, prices, brand }) => {
          return (
            <ProductCard
              key={id}
              id={id}
              name={name}
              inStock={inStock}
              gallery={gallery}
              prices={prices}
              brand={brand}
            />
          );
        })}
      </div>
    );
  }
}

This is working fine when I change routes reloading the page. But when I change routes through nav links in my Header, the props name is updated, but the rest of the application is not.

Specifically, the API call in componentDidMount() of CategoryBody.jsx is needed to be called again so that the items rendered in the component are the expected, according to the path.

I would like to know how can I “force update” a component when I change routes from inside the application.

Keep counter value to localStorage after page refresh

I have a countdown timer. This timer is called in an ajax call whenever user press a button.
I would like to set timer (countdown) in localStorage and get timer (countdown) after page refresh. Could you please help me to implement this in the below code?

const progressBox = document.getElementById('progress-box')

const activateProgress = (progress) => {

    if (progress.toString().length < 2) {
        progressBox.innerHTML = `<b>0${progress}:00</b>`
        progressBox.innerHTML = `<b>${progress}:00</b>`
    } else {
        progressBox.innerHTML = `<b>${progress}:00</b>`
    }
    
    let minutes = progress - 1
    let seconds = 60
    let displaySeconds
    let displayMinutes
    
    const timer = setInterval(()=>{
        seconds --
        if (seconds < 0) {
            seconds = 59,
            minutes --
        }
        if (minutes.toString().length < 2) {
            displayMinutes = '0' + minutes
        } else {
            displayMinutes = minutes
        }
        if (seconds.toString().length < 2) {
            displaySeconds = '0' + seconds
        } else {
            displaySeconds = seconds
        }
        if (minutes === 0 && seconds === 0) {
            setTimeout(()=>{
                clearInterval(timer)
                alert('Time Over')
            }, 500)
        }
        progressBox.innerHTML = `<b>${displayMinutes}:${displaySeconds}</b>`
    }, 1000)
}

const checkInForms = [...document.getElementsByClassName('checkin-forms')]
checkInForms.forEach(form=> form.addEventListener('submit', e=>{
    e.preventDefault()
    const clickedCheckinId = e.target.getAttribute('data-form-id')
    const clickedCheckinBtn = document.getElementById(`mark-checkin-btn-${clickedCheckinId}`)

    $.ajax({
        type: 'POST',
        url: "checkin/",
        data: {
            'csrfmiddlewaretoken': csrftoken,
            'pk': clickedCheckinId,
        },
        success: function(response){
            console.log(response)
            activateProgress(response.progress)
            localStorage.setItem('progress', response.progress)
        },
        error: function(error){
            console.log(error)
        }
    })
}))

Many Thanks

How to find out how many milliseconds until YouTube is ready?

You will notice that clicking on the play button too soon, and nothing happens. https://jsfiddle.net/zqrLxevo/

How the code works is: As soon as a video has loaded, click on the cover to start playing.

Is there a way to determine, or find out how many milliseconds it takes until youtube is ready?

How many milliseconds until the play button is able to be clicked?

I think it is higher than 500ms, but how is the number found out?

Is there a way I can attach something to it that will give me a number?

const manageCover = (function makeManageCover() {
  const events = {};

  function show(el) {
    el.classList.remove("hide");
  }

  function hide(el) {
    el.classList.add("hide");
  }

  function openCurtain(cover) {
    hide(cover);
    const curtain = document.querySelector(".curtain");
    curtain.classList.add("slide");
    return curtain;
  }

  function showVideo(curtain) {
    const thewrap = curtain.parentElement.querySelector(".wrap");
    show(thewrap);
  }

  function coverClickHandler(evt) {
    const cover = evt.currentTarget;
    const curtain = openCurtain(cover);
    showVideo(curtain);
    cover.dispatchEvent(events.afterClickCover);
  }

  function init(callback) {
    const cover = document.querySelector(".play");
    cover.addEventListener("click", coverClickHandler);
    events.afterClickCover = new Event("afterClickCover");
    cover.addEventListener("afterClickCover", callback);
  }

  return {
    init
  };
}());

const videoPlayer = (function makeVideoPlayer() {
  const events = {};
  const eventHandlers = {};
  let player = null;


  function loadIframeScript() {
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    const firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }

  function onYouTubeIframeAPIReady() {
    const cover = document.querySelector(".play");
    const wrapper = cover.parentElement;
    const frameContainer = wrapper.querySelector(".video");
    videoPlayer.addPlayer(frameContainer);
  }

  function shufflePlaylist(player) {
    player.setShuffle(true);
    player.playVideoAt(0);
    player.stopVideo();
  }

  function onPlayerReady(event) {
    player = event.target;
    player.setVolume(100);
    shufflePlaylist(player);
    const iframe = player.h;
    iframe.dispatchEvent(events.afterPlayerReady);
  }

  function addPlayer(video) {

    const playlist = "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g";

    const config = {
      height: 360,
      host: "https://www.youtube-nocookie.com",
      width: 640
    };
    config.playerVars = {
      autoplay: 0,
      cc_load_policy: 0,
      controls: 1,
      disablekb: 1,
      fs: 0,
      iv_load_policy: 3,
      loop: 1,
      playlist,
      rel: 0
    };
    config.events = {
      "onReady": onPlayerReady
    };

    player = new YT.Player(video, config);

    const iframe = player.h;
    const eventHandler = eventHandlers.afterPlayerReady;
    iframe.addEventListener("afterPlayerReady", eventHandler);
  }

  function play() {
    player.playVideo();
  }

  function addEvents(handlers) {
    eventHandlers.afterPlayerReady = handlers.afterPlayerReady;
    events.afterPlayerReady = new Event("afterPlayerReady");
  }

  function init(initEventHandlers) {
    addEvents(initEventHandlers);
    loadIframeScript();
    window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
  }

  return {
    addPlayer,
    init,
    play
  };
}());

videoPlayer.init({
  afterPlayerReady: function initCover() {
    manageCover.init(function playVideo() {
      videoPlayer.play();
    });
  }
});

Getting the file size of a file in javascript

<input id="archivo" name="archivo" type="file">

So my field of type file is called archivo which parent is formIncidencia, so what i’m doing to find it is:

$('#formIncidencia').find("[id='archivo']");

This works fine but when i’m trying to do:

 $('#formIncidencia').find("[id='archivo']").files[0].size; 

it’s not working like that, and i’m uploading a file so don’t know what it’s happening..

Created animation for title and subtitle transform translateY () with css

I am working on a project with vuetify I have created a background image cover over background image I have a title, subtitle and a button.

I should to created same effect animation with css:
Firstly, I should to display title with transform translate Y()
to be coming with animation

Secondly, I should to display subtitle with transform translate Y()
to be coming with animation with the same logic that first, but subtitle should, will be coming after title with some seconds.

For button, we don’t need for anyone animation transform translate Y() just to display in the same position after subtitle with same seconds.
I have done until now to create effect animation for all three element display together, I am sharing my code:

.slide-fade-1-enter-active {
    transition: all .7s ease-out;
}
.slide-fade-1-enter {
    transform: translateY(200px);
    opacity: 0;
}

.slide-fade-2-enter-active {
    transition: all 1s ease-out;
}
.slide-fade-2-enter {
    transform: translateY(200px);
    opacity: 0;
}

.slide-fade-3-enter-active, .slide-fade-3-leave-active {
    transition: opacity 1s;
}
.slide-fade-3-enter, .slide-fade-3-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
}
    <div class="hero-inner">
        <transition name="slide-fade-1" appear>
            @if ($block->input('title') != '')
                <h1 class="text-white "> {{ $block->input('title') }} </h1>
            @elseif($block->image('title_image'))
                <img class="hero-title-img" src="{!!$block->image('title_image', 'default', ['fm' => null])!!}">
            @endif
        </transition>
        <transition name="slide-fade-2" appear>
            @if ($block->input('subtitle') != '')
                <h3 class="text-white  mt-15"> {{ $block->input('subtitle') }} </h3>
            @endif
        </transition>
        <transition name="slide-fade-3" appear>
            @if ($block->input('cta_label') != '')
                <v-cta link="{!!$block->input('cta_link')!!}" label="{!!$block->input('cta_label')!!}"></v-cta>
            @endif
        </transition>
    </div>

But we want to  create exactly  affect animation transform translate  by UI/UX design in the Figma. enter link description here

Nodejs + Mysql, How do I find a name if already exist before inserting the name?

Hi I’m learning nodejs with mysql. I have crated a method to post a name in database. But now I want to execute another method which first check if name does not exist then run post name method

NOTE My table only containes ‘nick_names’ column

Here is my route in router file router.post(‘/’, NickNamesController.createName)

Actual result-> I can post names here: Controller.js

exports.createName = (req, res) => {
  const reqData = new NickNamesModel(req.body);
  NickNamesModel.addNewName(reqData , (err, name) => {
            if (err){
                return res.status(400).send(err.code);
            }
            res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
        });
  
}

Expected: Controller.js Please have a look here This is what I want to achieve

exports.createName = (req, res) => {
  const reqData = new NickNamesModel(req.body);

// first check if name exist or not?
  const ifExist = NickNamesModel.getNameIfExist(reqData.nick_name, (err, name) => {
       if(err){
           return err.code;
        }
      return name;
})

// checking if ifExist has 1 then value already exist. If 0 then not exist
  if(ifExist != 0) {
    return res.status(400).send({success: false, message: Duplicate Name});
} else {
  NickNamesModel.addNewName(reqData , (err, name) => {
            if (err){
                return res.status(400).send(err.code);
            }
            res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
        });
  }
  
}

NickNamesModel.js

NickNamesModel.addNewName = (reqData, result) => {
    dbConn.query('INSERT INTO nick_name_table SET ? ', reqData, (err, res) => {
        if (err) {
            console.log('Error while inserting name', err);
            result(err, null);
        }else {
            console.log('Name inserted successfully');
            result(null, res);
        }
    })
}

// Method to check if nick name already exist then return 1 else 0
NickNamesModel.getNameIfExist = (nick_name, result) => {
    dbConn.query('SELECT EXISTS('SELECT station_name FROM stations SET WHERE station_name=? LIMIT 1)', nick_name, (err, res) => {
        if (err){
            console.log('Error while fetching stations', err);
            result(null, err);
        } else {
            console.log('Stations fetched successfully');
            result(null, res)
        }
    })
}

Uncaught SyntaxError: Unexpected token u in JSON at position 0 while fetching data from localstorage [duplicate]

I’m new to react and in this simple ToDo app, I’m trying to fetch notes from localStorage and if they exist, assign it to react notes initial state. Here is the code:

import React, {useState, useEffect}   from 'react';
import ReactDOM from 'react-dom';


 
 const NoteApp = () => {
   const notesData = JSON.parse(localStorage.getItem('notes'));
   const [notes, setNotes ] = useState(notesData || []);
   const [title, setTitle] = useState('');
   const [body, setBody] = useState('');

   const addNote = (e) => {
     e.preventDefault();
    const note =  {
      id:Math.random(),  
      title: title,
       body: body}

     setNotes([...notes, note]);
     setTitle('');
     setBody('');
   }

   const removeNote = (title) => {
     setNotes(notes.filter(note=> (note.title !== title) ));
   }
   useEffect(()=> {    
   localStorage.setItem('notes', JSON.stringify(notes))
  });
  

   return ( 
     <div>
      <h1>Notes </h1>
      {notes && notes.map((note) => (
        <div key={note.id}>
          <h3>{note.title}  </h3>
          <p>{note.body}</p>
          <button onClick={()=> removeNote(note.title)}>x</button> <br />
        </div>
      ))}
 
     <form  onSubmit={addNote}>
       <input type="text" value={title} onChange={e => setTitle(e.target.value)} /><br /> <br /> 
       <textarea value={body} name="body" id="" cols="30" rows="10" onChange={e => setBody(e.target.value)}></textarea>
       <br /><br />
 
       <button>add note</button>
     </form>     
     </div>
    );
 }

 
ReactDOM.render(
  <React.StrictMode>
    <div>
      <NoteApp />
    </div>
  </React.StrictMode>,
  document.getElementById('root')
);

However I get a blank page and this massive error:

VM19427:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at NoteApp (index.js:7:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
NoteApp @ index.js:7
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:20085 The above error occurred in the <NoteApp> component:

    at NoteApp (http://localhost:3000/static/js/bundle.js:28:26)
    at div

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:4005 Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4005:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)
    at renderRootSync (react-dom.development.js:22670:1)
    at performSyncWorkOnRoot (react-dom.development.js:22293:1)
    at scheduleUpdateOnFiber (react-dom.development.js:21881:1)
    at updateContainer (react-dom.development.js:25482:1)
    at react-dom.development.js:26021:1
invokeGuardedCallbackDev @ react-dom.development.js:4005
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7

React wrong result on the change of state

I’m new to react and working on simple eCommerce application. I am changing the quantity of in the cart when it is added more than one times but it gives wrong result(As we can see in the output the ‘quantity’ I print and in the object are different eg. before:1 after:2 but in the object it is 3).I’ll appreciate any help. Thank You!!

here is my reducer.js

export const initialState = {
    basket : [],

}


const reducer = (state, action) => {
    switch(action.type){
        case "ADD_TO_BASKET":
            const newIndex = state.basket.findIndex((basketItem)=> basketItem.id==action.item.id)
            if(newIndex >= 0){
                const newBasket = [...state.basket];
                console.log(newBasket);
                console.log("quantity "+newBasket[newIndex].quantity);
                newBasket[newIndex].quantity+=action.item.quantity;
                console.log(newBasket);
                console.log("quantity "+newBasket[newIndex].quantity);
                return{
                    ...state,
                    basket: [...newBasket]
                }
            }
            return{
                ...state,
                basket: [...state.basket ,action.item]
            }
            .
            .
            .

export default reducer;

here is my checkout.js:

import { useStateValue } from "./StateProvider"
function Checkout() {
    const [{basket}, dispatch] = useStateValue();
return (
        <div className='checkout'>
            <div className="checkout__left">
                <img src="https://images-na.ssl-images-amazon.com/images/G/02/UK_CCMP/TM/OCC_Amazon1._CB423492668_.jpg" alt="" className="checkout__ad" />
                <div>
                    <h2 className='checkout__title'>
                        Your Shopping Basket
                    </h2>
                    {basket.map(item => (
                        // console.log("checkout product quantity: "+JSON.stringify(item.quantity)),
                        <CheckoutProduct 
                            key={i++}
                            id = {item.id}
                            title = {item.title}
                            image = {item.image}
                            price = {item.price}
                            rating = {item.rating}
                            quantity = {item.quantity}
                        />
                    ))}
 .
 .
 .

StateProvider.js:

import React, { createContext, useContext, useReducer } from 'react'

//prepares the data layer
export const StateContext = createContext();

//wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
);

//pull infromation from the data layer
export const useStateValue = () => useContext(StateContext);

Output in console:

-> [{…}]0: {---, quantity: 3}length: 1[[Prototype]]: Array(0)
-> quantity 1
->[{…}]0: {---, quantity: 3}---
-> quantity 2

How to solve ERR_TOO_MANY_REDIRECTS that is happening due to one middleware that forces https connection?

My middleware

exports.redirectToHTTPS = (req, res, next) => {
    if (req.protocol == "https") {
        return next()
    }
    const redirect_not = req.query.redirect
    
    console.log("!!!!! Connection not secure")
    const redirect_url = ['https://', req.get('host'), req.originalUrl].join('')
    console.log("REDIRECT_URL:- " + redirect_url)
    return res.redirect(redirect_url)
}

in index.js

app.use(redirectToHTTPS)

I am using express.js and node.js