What can I do so object.property doesn’t return undefined? [duplicate]

I’m trying to create a function that first fetches the JWT access tokens from my current session and then applies that to the Authorization header of my actual request.
This works fine, but the end result is that I want to return the full response object.

I’ve tried assigning some of the output to a output object, but when I try to console.log some of the properties, then it just returns undefined. If I do console.log inside the browser, then I can see the output but I can never print the actual properties.

export default function fetcher(url, method, body = null) {
  const output = {}
  fetch("/api/auth/session")
    .then((response) => {
      return response.json()
    })
    .then((data) => {
      const token = data.user.accessToken
      if (method.toLowerCase() == "post") {
        const res = fetch(url, {
          method: "post",
          headers: {
            Authorization: "Bearer " + token,
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
          },
          body: body,
        }).then((response) => {
          Object.assign(output, {
            status: response.status,
          })
        })
      } else {
        const res = fetch(url, {
          method: "get",
          headers: {
            Authorization: "Bearer " + token,
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
          },
        })
          .then((response) => response.json())

          .then((data) => {
            Object.assign(output, data)
          })
      }
    })
    .catch((err) => {
      // Do something for an error here
    })
  console.log(output)
  console.log(output.status)

  return output
}

Console.logs

End goal is to call the function from some other file like this

const test = fetcher("http://api.localhost/v1/projects", "post", JSON.stringify({ name: event.target.name.value }))

console.log(test.status)

Vitejs: WebSocket connection to ‘wss://host:port/’ failed due to HMR

I deployed a Vue with Docker and Kubernetes and it is working. However, even though I disabled HMR, Vite keeps refreshing after an error:

WebSocket connection to ‘wss://dashboard.default.io:8181/’ failed:

[vite] server connection lost. polling for restart…

Dockerfile:

FROM node:16-alpine3.14
WORKDIR /usr/src/app
COPY . .
RUN yarn install
EXPOSE 8181
CMD [ "yarn", "dev","--host", "--port", "8181" ]

vite.config.js:

export default defineConfig({
  plugins: [vue()],
  server: {
    hmr: false
  }
})

vue.config.js:

module.exports = {
    devServer: {
      proxy: 'https://backend.default.io'
    }
  }

I could not figure out why it is still using HMR since I disabled it. And, how can I fix this? I also tried server.hmr.clientPort: 443 but it also did not work.

How to get current string value from text field?

I have a problem. I have a method to automatically translate strings to chosen language via GoogleTranslate API. And I’ve met a problem, when user cannot translate value that he has written but not saved yet. For better understanding – here is part of my code

    <% Product::PRODUCT_RESOURCES.each do |resource| %>
      <% passed_resource = ""#{resource}"" %>
      <% passed_locales = @product.shop_short_locales %>
      <% passed_locales.delete("en") %>
      <% primary = product_resources_translations(@product.translatable_content, resource)  %>
      <% json_primary = ""#{primary.value}"" %>
      <% translated_locales = [] %>
      <% passed_locales.each do |locale| %>
          <% translated_locales.push(GoogleTranslator.translate(json_primary, locale)) %>
        <% end %>
      <div id="google_icon_div">
        <%= image_tag "google-icon.png", id: "google_icon", onclick: "test_transl(#{passed_resource}, #{passed_locales.to_json}, #{translated_locales.to_json})"%>
      </div>
      <%= raw labeled_text({
                             label_title: t(resource),
                             input_name: "primary_locale[#{resource}]",
                             input_value: primary&.value ? primary.value : '',
                             tag_type: ProductsHelper::PRODUCT_RICH_EDIT_RESOURCES.include?(resource) ? :textarea : :input})
      %>
    <% end %>
  </div>

and here is the my JS function:

  function test_transl(resource_value, locales_arr, json_primary){
      locales_arr = locales_arr.map(i => i.replaceAll('-','_'));
      locales_arr = locales_arr.map(i => resource_value + '_' + i);

      for (var i=0; i<locales_arr.length; i++)
      {
          my_div = document.getElementById(locales_arr[i])
          my_div.getElementsByTagName('textarea')[0].value = json_primary[i]
          my_div.getElementsByClassName('note-editable')[0].innerText = json_primary[i]

      }
  }

Basically, the problem can be described like this: the text box is already have a value ‘hello’ –> user enters new value ‘bye’ –> the other text box with translations will translate it as ‘hello’. So everything I need is to get somehow the CURRENT value of the text box – ‘bye’ and then to translate it and pass to JS.

CORS Error after deploying react app to netlify with Node/Express backend and MySQL in Heroku

Before I deploy, the app performed fine on localhost. But since I deployed my frontend (react) to Netlify and backend(node/express + mysql) to Heroku, all requests sent from the frontend started to get blocked by CORS policy, with the error message:

“Access to XMLHttpRequest at ‘https://xxx.herokuapp.com/login’ from origin ‘https://xxx.netlify.app’ has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header has a value ‘https://xxx.app/’ that is not equal to the supplied origin.”

Most importantly, the value of my Access-Control-Allow-Origin header is literally the same as the origin stated.

Originally, I’ve tried to use a wildcard (“*”), but it seems that due to the withCredential problem, the system just can’t allow that kind of vague statement.
I’ve also seen many people using Netlify.toml to tackle some configuration problems, but seems ineffective for me.

Is it the header’s problem? If not, then what is the problem?

I really want to know what I should do to solve this error…

My index.js in the server folder:

const express = require('express')
const mysql = require('mysql')
const cors = require('cors')
const session = require('express-session')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')

const port = 3010

const app = express()

app.use(express.json())
app.use(cors({
  origin: ["https://xxx.app/"], // the link of my front-end app on Netlify
  methods: ["GET", "POST"],
  credentials: true
}))

app.use(cookieParser())
app.use(bodyParser.urlencoded({
  extended: true
}))
app.use(
  session({
    key: "userId",
    secret: "subscribe",
    resave: false,
    saveUninitialized: false,
    cookie: {
      expires: 60 * 60 * 24
    },
  })
)

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "https://xxx.netlify.app/"); // the link of my front-end app on Netlify
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
  );
  res.setHeader('content-type', 'application/json');
  next();
});

const db = mysql.createPool({
  // create an instance of the connection to the mysql database
  host: 'xxx.cleardb.net', // specify host name
  user: 'xxx', // specify user name
  password: 'xxx', // specify password
  database: 'heroku_xxx', // specify database name
})

...

app.get('/login', (req, res) => {
  if (req.session.user) {
    res.send({
      isLoggedIn: true,
      user: req.session.user
    })
  } else {
    res.send({
      isLoggedIn: false
    })
  }
})

...

app.listen(process.env.PORT || port, () => {
  console.log('Successfully Running server at ' + port + '.')
});

My Frontend:

import React, { useEffect, useState } from 'react'
import '../App.css'
import './HeroSection.css'
import { Link } from 'react-router-dom'
import Axios from 'axios'

function HeroSection() {
  Axios.defaults.withCredentials = true
  let username = "";
  const [name, setName] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [isLoading, setLoading] = useState(true)
  
  ...
  
  useEffect(() => {
    Axios.get('https://xxx.herokuapp.com/login').then((response) => {
      if (response.data.isLoggedIn) {
        username = response.data.user[0].username;
      }
      setIsLoggedIn(response.data.isLoggedIn)
      Axios.post('https://xxx.herokuapp.com/getLang', {
        username: username,
      }).then((response) => {
        console.log(response.data);
      })
      Axios.post('https://xxx.herokuapp.com/getStatus', {
        username: username,
      }).then(response => {
        setName(response.data[0].firstname + " " + response.data[0].lastname);
        setLoading(false);
      })
    })
  }, [])

  if (!isLoggedIn || isLoading) {
    return (
      <div>
      ...
      </div>
    )
  } else {
    return (
      <div>
      ...
      </div>
    )
  }
}

export default HeroSection

By the way, I use ClearDB MySQL on Heroku and MySQL WorkBench for the database, which all works fine.

Show or hide navbar in php [closed]

For you, I would like some help with the navbar how can I make a Hide link from the navbar if its MySQL status is inactive that is, I want if its status is active to appear in the navbar and if it is unactive do not point to the navbar.

JavaWeb + JSF + Primefaces

Bom pessoALL,

Tenho uma aplicação JavaWeb, estou armazenando um valor pelo localStorage.
E quando chamar uma determinada página quero enviar esse valor para uma String que está em um Bean.

O JS terá um onload, então toda vez que a página for atualizada,quero que o Bean faça o tratamento desse valor.

Alguém pode me dar esse help!?

How to turn on/off the embla carousel by breakpoint in React?

Using the Embla Carousel, React version, I’m trying to turn/on off the carousel based on breakpoint. So for mobile, it’s on and for tablet up it’s off. Here’s what I tried that seems to work initially, but won’t reinitialize. I’m guessing it’s because destory was called so it can reInit and tried init, but no luck there either.

const emblaOptions = {};
  const [viewportRef, emblaApi] = useEmblaCarousel(emblaOptions);

  const handleEmblaInit = () => {
    if (window.innerWidth > 768) {
      emblaApi.destroy();
    } else {
      emblaApi.reInit(emblaOptions);
    }
  };

  useEffect(() => {
    if (emblaApi) {
      handleEmblaInit();
      window.addEventListener("resize", handleEmblaInit);
    }
  }, [emblaApi]);

How can i get Y position in all the website page

I have a website which is 6 viewports height.
I would like to get the Y position for no matter where i am in the page not only the viewport.
I have tried :

  • event.pageY ;
  • element.getBoundingClientRect();
  • window.innerHeight / outerheight;

It doesn’t solve my problem.

Thanks

JavaScript change function name by adding an increment number to it’s end [duplicate]

I’m trying to change function name by adding an increment number to it’s end each time it gets executed, to achieve a new function name each time the code is executed.

<button id="Btn">alert text</button>

function text1(){
    alert("This is text1");
}

function text2(){
    alert("This is text2");
}

function text3(){
    alert("This is text3");
}

var Btn = document.getElementById("Btn");
var i = 1;

Btn.addEventListener("click", function alertText(){

i++;

//bellow line in the first time should be text2()

text+i();

}

CSS input box cutting off text

I am having an issue where the text in this input box is being cut off. I’ve increased the height and the width and it is still showing the same amount of characters. I’ve also used page-break-after: always and the issue is not being fixed. Here is the code:

    input[division]{
        font-size: 13px;
        height: 70px;
        resize: none;
        text-align: center;
        page-break-after: always
        
    }
<div><p><b><br>Division:</b><input id='transfer_out_division' type='text' value="EMD - AFC Program & Information Management" top required division></input></p></div>

I would like the text to go to the next line once it reaches the end of the input box. I was trying to make the input box at least 3 lines long. It fits perfectly with but I do not want to use that element as when I go to print, it prints a line lower and I found it difficult to fix. Input seems as the easiest way to get the printing constraints as consistent as possible.

Adding variable getting error in gitlab ci/cd yaml script?

I’m having two variable {$KUBE_NAMESPACE_DEV} & {$KUBE_NAMESPACE_STAGE} =”stellacenter-dev” & “stellacenter-stage-uat” values respectively.
Now I want to add the variable in .gitlab ci/cd yaml script

deploy_dev:
  stage: deploy
  image: stellacenter/aws-helm-kubectl
  before_script:
    - aws configure set aws_access_key_id ${DEV_AWS_ACCESS_KEY_ID}
    - aws configure set aws_secret_access_key ${DEV_AWS_SECRET_ACCESS_KEY}
    - aws configure set region ${DEV_AWS_DEFAULT_REGION}
  script:
    - sed -i "s/<VERSION>/${CI_COMMIT_SHORT_SHA}/g" provider-service.yml     
    - mkdir -p  $HOME/.kube
    - cp $KUBE_CONFIG_DEV $HOME/.kube/config
    - chown $(id -u):$(id -g) $HOME/.kube/config 
    - export KUBECONFIG=$HOME/.kube/config
    - kubectl apply -f ./provider-service.yml 
  only:
    - developer  

Provide-service.yml file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: provider-app
  namespace: "stellacenter-dev" "stellacenter-stage-uat" 
  labels:
    app: provider-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app : provider-app
  template:
    metadata:
      labels:
        app: provider-app
    spec:
      containers:
      - name: provider-app
        image: registry.gitlab.com/stella-center/backend-services/provider-service:<VERSION>
        imagePullPolicy: Always
        ports:
          - containerPort: 8092
      imagePullSecrets:
        - name:  gitlab-registry-token-auth

---

apiVersion: v1
kind: Service
metadata:
  name:  provider-service
  namespace: "stellacenter-dev" "stellacenter-stage-uat" 
spec:
  type: NodePort
  selector:
    app:  provider-app
  ports:
  - port:  8092
    targetPort:  8092

I don’t know how to integrate the variables and the values correctly . I’m facing the error while I run pipeline.Kindly help me to sort it out.

Change color of text when div is transitioning through it

I want to implement a navbar element highlight using a div that moves (via transitions) to the selected element when you click on it.

But in addition, it should change the color of the text it passes through.

See this example (the red highlight is currently moving from “First” to “Second Text”, coloring the text inside the highlight white):

highlight transition show-case

I’ve made a small codepen to showcase a solution I came up with, which utilizes position: absolute and overflow: hidden.

See here: https://codepen.io/JZ_CodePen/pen/JjMzpye

Is there a simpler / more professional way to implement this?

Don’t close CSS popup when clicking on it

I am trying to add a form within a popup, but whenever you click the text box in the popup it closes and you cant type in the text box, is there a way to disable click to close? and only have it so clicking out the pop up it closes rather than within the pop up. I have tried to change the CSS of the myPopup and added ‘pointer-events:none’ but that disables click to all components within the popup.

<style>
/* Popup container - can be anything you want */
.popup {
position: relative;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

/* The actual popup */
.popup .popuptext {
visibility: hidden;
width: 180px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;
 height:200px;
}

/* Popup arrow */
.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
from {opacity: 0;} 
to {opacity: 1;}
}

@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
</style>

<body style="text-align:center">

<h2>Popup</h2>
<br><br><br><br><br><br><br><br><br><br><br><br>
<div class="popup" onclick="myFunction()">Click me to toggle the popup!
<span class="popuptext" id="myPopup"><input type="text" id="fname" name="fname"><br><br> 
<button> 
<button></span>
</div>

<script>
// When the user clicks on div, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
</script>