Property or method “length” is not defined on the instance but referenced during render

enter image description here
enter image description here
Under the visual-management.vue file, I did not find the “length” attribute, and all my functions on the page are running normally.
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

I’ ve looked around and apparently I’ve got the choice between these libraries

Using custom data in preflight request to get dynamic origin URL

I’m using express to handle my routes and have CORS enabled for some routes, due to needing to send custom headers and complex request types.

On app start, I do the following:

app.use(function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
    res.setHeader("Access-Control-Allow-Headers", `X-Requested-With, Content-Type, ${customHeaders.join(", ")}`);
    res.setHeader("Access-Control-Allow-Credentials", true);
    next();
});

My routes look something like:

router.get("api/v1/user/current", customerMiddleware, controllers.Customer.get)

My application can be hosted on my clients’ websites, with each client being able to set the Origin Urls that they’ll be using my application from. These custom Origin Urls are saved on a customer basis.

I have a middleware on my route which checks the Authorization and the customer’s unique token (sent via custom header). Once they’ve been auth’d, I add their customer data onto the request object, something like:

const customer = await getCustomerByToken(req.headers['Customer-Token']);
const origin = req.headers.origin;
const { allowOriginUrls = [] } = customer;

if (allowOriginUrls.includes(origin)
    || whiteListedOrigins.includes(origin)
    || whiteListedOrigins[0] === "*"
) {
    res.setHeader("Access-Control-Allow-Origin", origin);
}
req.customer = customer

Eventually, if the request coming in is CORS enabled, then this middleware will look through the customer’s custom origin urls, and set the Allow Origin header to be the referrer url if it’s found.

Currently, the server sends “*” as the Allowed Origin as the default, when it would be overwritten with the above middleware if successful.

My issue is that, because the customer’s unique token is sent via the custom header, this isn’t available in the preflight OPTIONS request, meaning I never have the data to send the customer’s origin url in the response. Resulting in:

Access to XMLHttpRequest at 'https://serverdomain.com/api/v1/users/current' from origin 'https://clientdomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Is there a way that I’m able to somehow identify which customer is requesting the route during the Preflight OPTIONS request so I can provide the proper origin url in the response?

I tried accessing the request data and headers in the OPTIONS route, but it didn’t include the data that I needed to be able to identify which URL was allowed.

I recognised that I could just respond with the referrer url sent with the OPTIONS request, but that makes my custom Origin Urls kind of redundant, as the app would be allowed to request from any site that it’s included on.

From a SQL Query, assign the value to a JS variable [duplicate]

I’m trying to assign a specific value from my SQL query to a variable, but it return undefined.

function getHeroStats(){
    sql.connect(config, err => {
        if (err) console.log(err);

        const request = new sql.Request();
        // query to the database and get the data
        request.query('Select * From Hero', (err, res) => {
            if (err) console.log(err);
            // send data as response
           return res.recordset[0].Name;
            // return res.recordset[0];
        });
    });
}

let hero = getHeroStats();
console.log(hero);

Hero is returning undefined and it should get a value from the SQL table.

How to echo sum values of different column using where condition with minimum php coding?

I have created school exam result database, it consists of different subjects marks viz chemistry1, chemistry2 for 8 examinations. I successfully echoed individual marks value on the same page through selection of class section and subject drop down menu by submit button. I want to show the cumulative result for example pass percentage, average for Male, female, total for all these 8 exams on same page.

I could did this through these type of code
$ab50query_am = "SELECT * FROM test_2324 where (chem1_1 >50 AND sub1_4<81) AND cls='$cls_show' AND sex='M' AND (section='$sect_show' )";$resab50=mysqli_query($db,$ab50query_am); $ab50val = mysqli_num_rows($resab50); For this i need to use more coding for each category and exam. Is there any array type php script available to achieve this.. awaiting for the help

Is it possible to hide/filter api response properties based on user role in nodejs

Is it possible to filter out the api response json properties based on user role (rbac) in nodejs without using a for loop?

For example I have this returning from an api endpoint

User: {
  name: string,
  email: string,
  address: string,
  dateOfBirth: string,
  gender: string
}

And I only want roleA to receive the fields name and gender, and roleB to receive the fields name, email, gender and address in the response json.

Are there any rbac libraries that can achieve this or any way to achieve this without looping through and checking each field?

Don’t receive the last state value

I have a custom hook called useMetrics which has 2 main functions:

  • updateMetricsBy: modifies a local state which will be used to save data to the server
  • saveMetrics: saves data to the server

The problem is saveMetrics receives an old metrics state value for some reason. That’s why we can investigate that the first calling won’t update anything on the server:

console picture

Codesandbox link: https://codesandbox.io/s/spring-browser-nynxp7?file=/src/App.js

Trying to put radio buttons inside a radio button

Basically, I’m following this post of mine and the following solution works fine if I have to display radio buttons and the and display divs inside it :

$(".tier1-options :radio").on("change", function (e) {
  //remove shown class from all tier2 options and clear values from all form elements inside it
  $('.tier2-options')
    .removeClass('shown')
    .find('input, select').val('')
  
  //show the related tier2 options
  $(this)
    .parents('.tier1-options')
    .find('.tier2-options')
    .addClass('shown')
});
.tier2-options {
  display: none;
  margin-left: 1rem;
  padding: 1rem;
  background-color: #EEE;
}

.shown{
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h5>Select one of the checkboxes:</h5>

<div class='tier1-options'>
  <label>
    <input name="useroption" type="radio" value="changeLocation">
    Change Location
  </label>

  <div class="tier2-options">
    <select name="availableMarkAsFullLocations">
      <option value="-">--Please Select--</option>
      <option value="3">BOX#3</option>
      <option value="6">FREEZER#1</option>
      <option value="8">FREEZER#2</option>
      <option value="19">BOX#9</option>
      <option value="20">QBUILDING</option>
    </select>
  </div>
</div>

<div class="tier1-options">
  <label>
    <input name="useroption" type="radio" value="updateLocation">
    Update Location
  </label>

  <div class="tier2-options">
    <select name="availableUpdateLocations">
      <option value="-">--Please Select--</option>
      <option value="3">BOX#3</option>
      <option value="6">FREEZER#1</option>
      <option value="8">FREEZER#2</option>
      <option value="19">BOX#9</option>
    </select>
  </div>
</div>


<div class="tier1-options">
  <label>
    <input name="useroption" type="radio" value="retireLocation">
    Retire
  </label>

  <div class="tier2-options">
    <select name="availableRetireLocations">
       <option value="-">--Please Select--</option>
       <option value="3">BOX#3</option>
       <option value="6">FREEZER#1</option>
       <option value="8">FREEZER#2</option>
       <option value="19">BOX#9</option>
       <option value="20">QBUILDING</option>
    </select>
  </div>
</div>

But when I’m trying to add multiple radio buttons, this code isn’t working for Move Contents option. Basicaly the subtier2-options won’t show up when I click on Tier I Move or Tier II Move

$(".tier1-options :radio").on("change", function (e) {
      //remove shown class from all tier2 options and clear values from all form elements inside it
      $('.tier2-options')
        .removeClass('shown')
        .find('input, select').val('')
      
      //show the related tier2 options
      $(this)
        .parents('.tier1-options')
        .find('.tier2-options')
        .addClass('shown')
    });
    
    $(".subtier1-options :radio").on("change", function (e) {
      //remove shown class from all tier2 options and clear values from all form elements inside it
      $('.subtier2-options')
        .removeClass('shown')
        .find('input, select').val('')
      
      //show the related tier2 options
      $(this)
        .parents('.subtier1-options')
        .find('.subtier2-options')
        .addClass('shown')
    });
    
    
    .tier2-options {
      display: none;
      margin-left: 1rem;
      padding: 1rem;
      background-color: #EEE;
    }

    .shown{
      display: block;
    }
    
    .subtier2-options {
      display: none;
      margin-left: 1rem;
      padding: 1rem;
      background-color: #EEE;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <h5>Select one of the checkboxes:</h5>

    <div class='tier1-options'>
      <label>
        <input name="useroption" type="radio" value="changeLocation">
        Change Location
      </label>

      <div class="tier2-options">
        <select name="availableMarkAsFullLocations">
          <option value="-">--Please Select--</option>
          <option value="3">BOX#3</option>
          <option value="6">FREEZER#1</option>
          <option value="8">FREEZER#2</option>
          <option value="19">BOX#9</option>
          <option value="20">QBUILDING</option>
        </select>
      </div>
    </div>

    <div class="tier1-options">
      <label>
        <input name="useroption" type="radio" value="updateLocation">
        Update Location
      </label>

      <div class="tier2-options">
        <select name="availableUpdateLocations">
          <option value="-">--Please Select--</option>
          <option value="3">BOX#3</option>
          <option value="6">FREEZER#1</option>
          <option value="8">FREEZER#2</option>
          <option value="19">BOX#9</option>
        </select>
      </div>
    </div>


    <div class="tier1-options">
      <label>
        <input name="useroption" type="radio" value="retireLocation">
        Retire
      </label>

      <div class="tier2-options">
        <select name="availableRetireLocations">
           <option value="-">--Please Select--</option>
           <option value="3">BOX#3</option>
           <option value="6">FREEZER#1</option>
           <option value="8">FREEZER#2</option>
           <option value="19">BOX#9</option>
           <option value="20">QBUILDING</option>
        </select>
      </div>
    </div>

    <div class='tier1-options'>
      <label>
        <input name="useroption" type="radio" value="moveContents">
        Move Contents
      </label>

        <div class="tier2-options">
             <div class='subtier1-options'>
                 <label>
                  <input name="useroption" type="radio" value="moveContentsTierI">
                  Tier I move
                </label>

                 <div class="subtier2-options">
                     <select name="availableTierILocations">
                     <option value="-">--Please Select--</option>
                     <option value="3">BOX#3</option>
                     <option value="6">FREEZER#1</option>
                     <option value="8">FREEZER#2</option>
                     <option value="19">BOX#9</option>
                     <option value="20">QBUILDING</option>
                  </select>
                 
                 </div>
                
             
             </div> <!--end of <div class='subtier1-options'> -->
             
             <div class='subtier1-options'>
                 <label>
                  <input name="useroption" type="radio" value="moveContentsTierII">
                  Tier II move
                </label>

                 <div class="subtier2-options">
                     <select name="availableTierIILocations">
                     <option value="-">--Please Select--</option>
                     <option value="3">BOX#3</option>
                     <option value="6">FREEZER#1</option>
                     <option value="8">FREEZER#2</option>
                     <option value="19">BOX#9</option>
                     <option value="20">QBUILDING</option>
                  </select>
                 
                 </div>
                
             
             </div> <!--end of <div class='subtier1-options'> -->
             
             
        </div>
    </div>

Vue SPA needs to access LAN devices – CORS Issue?

In a new Vite/Vue3 SPA, I got everything working correctly on my local machine which sits on a LAN. When I moved it to the WAN on a cloud IIS server (public address) the app loads but functionally when I try to issue a CGI commands a device on the LAN, I get error messages about CORS and cross domain security.

The application basically issues JavaScript Fetch() commands to turn up/down the volume on a Barix music player. The music player(s) each have a unique IP address on the LAN. The devices all have local dedicated web servers. ( for example see: https://www.barix.com/product/exstreamer-200-205/ ) (FYI The Barix technical reference that lists all the commands can be found at streaming_client_technical_documentation_v3_22.pdf

adjVolume(ipAddr,level){
   fetch('http://192.168.1.'+ipAddr+'/rc.cgi?V='+level, {mode:"no-cors"})
   .then(msg => console.log(msg))
}

Wondering if anyone has any suggestions how to get around the CORS blockage? So far my only thought is to put a small server on the LAN and install the application onto it. Really would like to run the application out of the cloud so as I start to add video cameras and other devices like A/D sensors and relays, I don’t have to maintain a remote server myself.

Thank you in advance for any comments or suggestions.

Is it possible to convert a .txt file to a google doc in an apps script? I keep throwing errors and I’m wondering what I’m missing

I commented out my attempt as it keeps failing… any thoughts?

    // script to be run on below noted folder and output to second specified folder in same drive
   // converts spreadsheets to TXT files



    function convertSpreadsheetsToDocs() {
    var mainFolderName = "Test Spreadsheets"; // Replace with your main folder name
    var subFolderName = "Subfolder5"; // Replace with your subfolder name

    var mainFolder = DriveApp.getFoldersByName(mainFolderName).next();
    var subFolder = mainFolder.createFolder(subFolderName); // Create a subfolder

     var spreadsheets = mainFolder.getFilesByType(MimeType.GOOGLE_SHEETS);

     while (spreadsheets.hasNext()) {
     var spreadsheet = spreadsheets.next();
     var spreadsheetName = spreadsheet.getName();
     var docName = spreadsheetName + " (Converted)";
     var doc = DocumentApp.create(docName);

     var sheet = SpreadsheetApp.openById(spreadsheet.getId()).getActiveSheet();
     var dataRange = sheet.getDataRange();
     var values = dataRange.getValues();
        dataRange.setNumberFormat("@"); // Set cell format as plain text


     var text = values.map(row => row.join("t")).join("n"); // Convert data to tab-delimited     text

    // Replace carriage return with page break
    text = text.replace(/n/g, "nn");

    // Replace tab with carriage return
    text = text.replace(/t/g, "n");



    var blob = Utilities.newBlob(text, MimeType.PLAIN_TEXT);
     //   var blob = Utilities.newBlob(text, MimeType.GOOGLE_DOCS);

    var docFile = subFolder.createFile(blob.setName(docName + ".txt"));


    // File.setContentType(MimeType.GOOGLE_DOCS);


    DriveApp.getFileById(doc.getId()).setTrashed(true); // Delete the temporary Google Doc
  }
// Replace text with carriage return
  //  text = text.replace("Note DatenNote TimenNoteTypenz_Created_BynContactPersonnNote Text", "The Shefa School");
 // Gets the document body.
//const body = doc.getBody();
// Deletes the first 10 characters in the body.
 //const text = body.editAsText().deleteText(0, 9);
  //  var docFile = subFolder.createFile(blob.setName(docName + ".txt"));
  //    setFontFamily(Arial);

  Logger.log("Spreadsheets converted to text file successfully.");
}

I can create the .txt file from a spreadsheet but fail when trying to make it a google doc. In the end I need to add some formatting… remove the first five or so lines and tag a font to it to make it pretty

Dynamically added not displaying correctly

This is the code to display website and a company logo below it from API.

The website of the company is displaying correctly but the company logo is not being displayed. What is the mistake in this code?

var website = null;
if (member.website) {
  website = $("<p/>", { class: "center website" });
  website.append(
    $("<img/>", {
      src: "/wp-content/themes/Divi-child/images/website.png",
      width: "20px",
      height: "20px",
    }),
  );
  var websiteAnchor = $("<a/>", { href: member.website, target: "_blank" });
  websiteAnchor.text(" " + member.website);
  website.append(websiteAnchor);
}

var companyImage = null;
if (member.companyImage && member.companyImage.image) {
  companyImage = $("<div/>", { class: "company-logo" });
  companyImage.append(
    $("<img/>", {
      src: "data:image/jpeg;base64," + member.companyImage.image,
      width: "200px",
      height: "auto",
    }),
  );
}

I have tried using the URL but no luck

js calculator project result undefined error

After building the calculator it’s supposed to sum up after pressing the equal sign but instead it shows “2+3undefined”

The equal button is not functioning properly, instead of the result its shows undefined error

let screen = document.querySelector('.screen');
let buttons = document.querySelectorAll('.btn');
let clear = document.querySelector('.btn-clear');
let equal = document.querySelector('.btn-equal');

buttons.forEach(function(button) {
    button.addEventListener('click', function(e) {
      let value = e.target.dataset.num;
      screen.value += value;
    })
  }

);

equal.addEventListener('click', function(e) {
  if (screen.value === '') {
    screen.value = "";
  } else {
    let answer = eval(screen.value);
    screen.value = answer;
  }
})

clear.addEventListener('click', function(e) {
  screen.value = "";
})

Is Cloudfront configurations be used to handle what Microfrontend applications I

AWS Cloudfront has capability to configure path to multiple S3 assets which can be like react application maintained by multiple teams.

If this is the case, why would teams using AWS ever use micro frontend when Cloudfront can do it.

I have a single requirement, but I am not sure which is best suited. I know single spa can help here, but I have knowledge gap what additional benifits we will get. We are using authentication as well.

using single spa as Microfrontend worked. clo

is decoupling nestjs class validation from pipes a good idea?

so when learning nest i got recommended by the docs on using dtos, pipes and class-validator for validating incoming payloads from requests

since then i was thinking about the possibility of having a service call from other places within the system other than http requests. i still had to validate the incoming payload, but since the validation logic is placed inside a pipe, the service was left not validated.

then i thought maybe creating another provider just for validating and decoupling the validation logic from the controller using the already installed by default class-validator and class-transformer packages

something like that for the service:

@Injectable()
export class RandomEntityService {
  constructor(
    @InjectRepository(RandomEntity) private randomEntityRepo: Repository<RandomEntity>,
    private randomEntityValidator: RandomEntityValidatorService,
  ) {}

  public async create(randomEntDto: RandomEntityCreateDto) {
    try {
      await this.randomEntityValidator.createValidation(randomEntDto);
    } catch (err) {
      throw new BadRequestException(err.message);
    }

    return this.randomEntityRepo.save(this.randomEntityRepo.create(randomEntDto));
  }

}

and something like that for the validator:

@Injectable()
export class RandomEntityValidatorService {

  public async createValidation(plainObject: Partial<RandomEntityCreateDto>) {
    const instance = plainToInstance(RandomEntityCreateDto, plainObject);

    const err = await validate(instance);

    if (err.length) {
      console.log(
        err.reduce((acc, e) => {
          acc.push(e.constraints);
          return acc;
        }, []),
      );
      throw new Error(err.toString());
    }
  }
}

not sure yet about error handling because it would have to be treated accordingly to whom called it i guess? but that is for tomorrow.

i mean, that way could i safely assume that calling the entity creation method from any other places would work and therefore save the pipe for other kinds of “http domain” logic? and that technically i am actually bringing business logic closer from outside providers to actual modules/providers?

never seen implemented that way but it may actually work and it makes some sense in my head.

and i kinda got stuck with the dto as data transfer object as a valid terminology for this “pattern” since the calling argument could actually be a dto from http or a plain object from let’s say a cron routine. not sure about that either.

is this approach valid considering good practices and node modularization patterns?

JS undefined: access primitive value of undefined without property?

I’m learning JavaScript (JS). I came across that undefined (such as from MDN) is a global property that refers to the undefined primitive value. I’ve seen this, for example, with the behavior of the delete operator:

When experimenting with the delete operator, I found that in non-strict mode:
delete undefined
evaluates to false (as opposed to delete null or another such attempted deletion of a primitive, which evaluates to true), whereas in strict-mode, it throws a SyntaxError: Delete of an unqualified identifier in strict mode.

My question is whether there is a way to access the “raw” undefined primitive value that the undefined property refers to in a way that can be directly written? For instance, when writing undefined in a JS program, that is actually referencing the global property whose value represents that primitive undefined value; I’m wondering if there is a way to directly write that undefined primitive value into a JS program, without going through such a reference? (For instance, like how true and false are Boolean primitives; can we actually write the undefined primitive in JS without accessing it via its same-named property?)