“[object Object]” Error when calling value from object in JavaScript

I’m building a weather app that fetches data from openweather, part of the data is the country code. I have built an object with the country codes and I would like to use the API to directly fetch the country from my object but i get [Object object] errors and i dont really understand it after several hours of googling. Also I’m new to JavaScript and coding in general still I don’t realize why this doesn’t work, maybe data.sys.country needs to be resolved first before object countries can be called?

countries = {
    US = "USA"
    GB = "United Kingdom"
};

//API
country = data.sys.country;
countryDisplay = countries.country;

console.log(country) = GB
console.log(countries.GB) = United Kingdom
console.log(countries.country) = [object Object].GB

I tried converting country to a string using JSON.stringify() but that just returned the country code in quotes. I also tried with;

countryDisplay = countries + "." + country

same result.

How can I debug a CORS request error with Discord webhooks in my HTML and JavaScript code?

I am testing out the web hooks, specifically Discords, and with a very simple site containing one HTML page and no extra JS files. The HTML files only run JS with <script> tag. It specifically returns the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://discord.com/api/webhooks/WebhookPartA}/{WebhookPartB}. (Reason: CORS request did not succeed). Status code: (null).

My code is :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <font size="+8">404</font>
    <title>404</title>
  </head>

  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script>

        fetch(
  'https://discord.com/api/webhooks/WebhookPartA}/{WebhookPartB}',
  {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      // the username to be displayed
      username: 'webhook',
      // the avatar to be displayed
      avatar_url:
        'https://cdn.discordapp.com/avatars/411256446638882837/9a12fc7810795ded801fdb0401db0be6.png',
      // contents of the message to be sent
      content:
        'test',

    }),
  }
);
      
    </script>
  </body>
</html>

I have tried both fetch() API and XMLRequests.

TypeScript Generic

I am fairly new to TypeScript and I have a problem understanding why the following is not working. Basically I have the following two Entities:

  • Item – This represents an item.
  • Inventory – This represents an storage where an Item can be stored in.

Items can be stored in different locations, in the example below I specified HEAD | TORSO | ARM.

An Inventory can either store all items or items that have a particular location.

For these requirements I ended up with the following:

type ILocation = 'HEAD' | 'TORSO' | 'ARM'

type IItem = {
    name: string
    location: ILocation
}

type IItemProps = {
    name: IItem['name']
    location: IItem['location']
}

type IInventory<TLocation = ILocation> = {
    items: Array<Omit<IItem, 'location'> & { location: TLocation }>
    addItem: (item: Omit<Item, 'location'> & { location: TLocation }) => void
}

type IInventoryProps<TLocation = ILocation> = {
    items: IInventory<TLocation>['items']
}

class Item implements IItem {
    private _name: string
    private _location: ILocation

    constructor(props: IItemProps) {
        this._name = props.name
        this._location = props.location
    }

    get name () {
        return this._name
    }

    get location () {
        return this._location
    }
}

class Inventory<TLocation extends ILocation = ILocation> implements IInventory<TLocation> {
  private _items: Array<Omit<IItem, 'location'> & { location: TLocation }>;

  constructor(props: IInventoryProps<TLocation>) {
    this._items = props.items;
  }

  get items() {
    return this._items;
  }

  addItem(item: IItem & { location: TLocation }) {
    this._items.push(item);
  }
}

I am trying to add a new item like this:


const inv = new Inventory<'HEAD'>({ items: [] })
const item = new Item({ name: 'CAP', location: 'HEAD' })
inv.addItem(item) // This is giving me an error

But it is giving me the following error:

Argument of type 'Item' is not assignable to parameter of type 'IItem & { location: "HEAD"; }'.
  Type 'Item' is not assignable to type '{ location: "HEAD"; }'.
    Types of property 'location' are incompatible.
      Type 'ILocation' is not assignable to type '"HEAD"'.
        Type '"TORSO"' is not assignable to type '"HEAD"'.

Not sure what’s going on.

I would like to know why this is happening and how to fix it.

create dynamic html templates to serve all clients in my django project

I created a customer registration system for a monthly water consumption billing system
now my system for each customer that I add I have to create a new table in the database and create the same html templates again to be able to work on the entire billing process
now I have to change the way of adding a customer so I don’t have to make several forms for each customer now I want to make a single form to serve all customers and I will also make a single table in the database to register more customers a billing table which will have the client’s foreign key
so I don’t know how to start making dynamic forms just click on it to open the form and show only the customer data I want to invoice
I ask for help on how to do this process

Uncaught ReferenceError: test1 is not defined

HTML file:

<html>

<head>
  <title></title>
  <script lanuage='javascript' ;src="test.js"></script>
</head>

<script language="javascript">
  test1(1, 2));
</script>

<body>
  <p id="t">test page for p server</p>
</body>
</html>

test.js file:

function test1(x, y) {
  var x, y;
  z = x + y
  document.write('z: ', z)
  return (z)
}

error appearing on the browser is Uncaught ReferenceError: test1 is not defined

This error does not come when I have the function inside the .html file. I want to have the function in the linked .js and was wondering how I could resolve this issue.

Canvases content is lost when the context is lost

I want to draw on canvases (more than 100) and have their content preserved. My setup is that I create canvases in a loop, and for each one I get the webgl2 context of it and do some drawing. The problem is, that after 16 canvases, when i get the webgl2 context from the 17th, the first one shows a missing image logo

enter image description here

I first thought that I should gracefully free up and release the context, but after googling a while, my only luck was to find some hack to call loseContext() on an extension, which ended in making the canvas look like the one in the image right after the call.

I also tried deleting all the resources used in the context (like buffers, programs and etc.) but no luck there either.

So, how do I achieve that? Is it possible at all?

Creating a dropdown menu that switches between tableau projects in my react app

i have a react app embedded with tableau dashboard presenting a certain project which is defined by the file of the tableau, i need to create a dropdown menu that switches between different tableau projects, which means it takes different urls based on the folder specified for it in the dropdown optinos and populates the app accordingly.

The embedding is happenning through a url in this manner:

import React from 'react'
import "../App.css"
import TableauView from 'insights-tableau';

function Finance() {
  return(<div className='MainDashboard'>
    <div className='dashboard-container'>
    <TableauView src="https://isr-tableau/views/Demo/Finance" toolbar="hidden" />
    </div>
    </div> )
}

export default Finance

and i have different views arranged inside the app in this way:

import { createRoot } from "react-dom/client";
import {
  createBrowserRouter,
  RouterProvider,
  Outlet,
} from "react-router-dom";

import MonitoringOverview from "./routes/MonitoringOverview";
import PerformanceQuality from "./routes/PerformanceQuality";
import Finance from "./routes/Finance";
import Navbar from "./components/Navbar/Navbar";
import "./App.css";
import LoginScreen from "./routes/LoginScreen/LoginScreen";
import UserConfig from "./routes/UserConfig/UserConfig.js";
import Simulation from "./routes/Simulation";
import Fraud from "./routes/Fraud";
import Deployment from "./routes/Deployment";
import Planning from "./routes/Planning";
const AppLayout = () => (
  <>
    <Navbar />
    <Outlet />
  </>
  
);








const router = createBrowserRouter([
  {
    path: '/',
    element: <LoginScreen />
  },
  
  
  {
    element: <AppLayout />,
    children: [
      {
        path: "monitoringoverview",
        element: <MonitoringOverview />,
      },
  
      {
        path: "performancequality",
        element: <PerformanceQuality />,
      },

      {
        path: "finance",
        element: <Finance />,
      },
      {
        path: "simulation",
        element: <Simulation />,
      },
      {
        path: 'userconfig',
        element: <UserConfig />
      },
      {
        path: 'fraud',
        element: <Fraud />
      },
      {
        path: 'deploymentrecommendations',
        element: <Deployment />
      },
      {
        path: 'planning',
        element: <Planning />
      }


      
    ],
  },
]);

createRoot(document.getElementById("root")).render(
  <RouterProvider router={router} />
  

and the navbar also needs to populate itself with the relevant project tabs

How should i approach this? i thought a state for the app for each project and the dropdown switches between these states, if this is my best option how should i do it and if there is a better way please let me know.

Thanks in advnace

AWS CloudWatch RUM integration in React Package

I was trying to track client side logs & errors and my web service is deployed in ec2 machine AWS in ap-south-1(Mumbai)region.

AWS CloudWatch RUM is one option for the logs-dashboard thing but while implementing i got to know that it is not available in ap-south-1(Mumbai)region.

Is their any way through which i can integrate RUM in ap-south-1(Mumbai)region?

Is there any other option that i can explore in AWS for the client side logging and dashboard.

Thanks for the help in advance.

Added the script in my webservice package

<script>(function(n,i,v,r,s,c,x,z){x=window.AwsRumClient={q:[],n:n,i:i,v:v,r:r,c:c};window[n]=function(c,p){x.q.push({c:c,p:p});};z=document.createElement('script');z.async=true;z.src=s;document.head.insertBefore(z,document.getElementsByTagName('script')[0]);}).....
but while creating the monitor in AWS cloudwatch, the RUM is not available in ap-south-1(Mumbai)region.

File Upload doesn’t work in Mobile web view ASP.NET MVC

For my project, I have used the multiple file upload using this https://github.com/fyneworks/multifile#tab-Download

This worked perfectly fine in the web view.

In the web view, when I select a file, the file name will appear below the choose file button.

But when I open it in mobile view using the browser, I can select the file, but it won’t add ed.

Also, I checked the controller as well, and there were also no files sent from the view even though I added some.

But working in the normal web view there is nothing error. working fine.

Can I know any reason this happening?

<div class="form-group">
  <label class="font-weight-bold" style="color:red">Please upload the task related all documents, if you have it now (Not Mandatory) <br />Maximum size for one document is 5 Mb </label>
  <input id="files" name="files" value="@Model.files" type="file" class="multi maxsize-5120" accept="jpg|pdf" multiple="multiple" />
</div>

Is there any proper way to give a shadow effect on the top portion of a card view in React Native in Android OS?

I have a Tab View which is placed just above the system default navigation icons on the screen. I want to create a Shadow Effect on the top part of the view. I have tried many ways, but react native does have only elevation property in android. And the elevation property is capable of giving the shadow effect on the bottom and the sides. I don’t want to use any library. Is there any possible solution to this problem?

Here is my code:

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, Dimensions, Image, SafeAreaView, View } from 'react-native';
const { height, width } = Dimensions.get('window');

const Home = () => {
  return (
    <SafeAreaView style={styles.mainContainer}>
      <View style={{ overflow: 'hidden' }}>

        <View style={[styles.floatingView, styles.floatingShadow]}>
          <Text style={{color: '#000'}}>Hello React native</Text>
        </View>

      </View>
    </SafeAreaView>
  )
}

export default Home;

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    backgroundColor: '#fff',
  },
  floatingView: {
    backgroundColor: '#B4F8C8',
    marginTop: height * 0.94,

    // position: 'absolute',
    // left:0,
    // right:0,
    // top:0,
    // bottom: 0,
    height: height * 0.06,
    width: "100%",
    alignSelf: 'center',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  floatingShadow: {
    shadowColor: "black",
    shadowOffset: {
      width: 10,
      height: 28,
    },
    shadowOpacity: 0.44,
    shadowRadius: 10.32,
    elevation: 26,
  }
})

Also, the screenshot to have a reference of what I am trying to say,

I tried with the elevation property and other react native functionalities. You can have a glimpse from my code. If I place the Tab View on the middle part of the screen, I can somehow block the bottom shadow but could not implement the top one. Any guidance or advise would be greatly appreciated.

is not a component. All component children of must be a or at invariant (history.ts:48

I was trying to make privateRoute on React. I want to control user roles and users can’t access every components. But i got an error like that ;

[ProtectedRoute] is not a component. All component children of
must be a or <React.Fragment>

and here my routes ;

const ProtectedRoute = ({ children, roles }) => {
    const { currentUser } = useAuth();

    if (!currentUser || (roles && !roles.includes(currentUser.role))) {
        return <NotFound />;
    }

    return children;
};

const App = () => {
    return (
        <div>
            <AuthProvider>
                <BrowserRouter>
                    <Routes>
                        <Route path="/" element={<Login />} />
                        <Route path="*" element={<NotFound />} />
                        <Route
                            path="/adminanasayfa"
                            element={
                                <React.Fragment>
                                    <ProtectedRoute roles={['admin']}>
                                        <AdminPage />
                                    </ProtectedRoute>
                                </React.Fragment>
                            }
                        />
                        <Route
                            path="/karaliste"
                            element={
                                <React.Fragment>
                                    <ProtectedRoute roles={['admin']}>
                                        <AddBlackListCar />
                                    </ProtectedRoute>
                                </React.Fragment>
                            }
                        />
                        <Route
                            path="/misafirarac"
                            element={
                                <React.Fragment>
                                    <ProtectedRoute roles={['admin']}>
                                        <AddGuestCar />
                                    </ProtectedRoute>
                                </React.Fragment>
                            }
                        />
                    </Routes>
                </BrowserRouter>
            </AuthProvider>
        </div>
    );
};

export default App;

i tried to change Routes but i couldn’t

Is possible to pass an input image from an html form to MATLAB using JavaScript?

I’m building a graphic interface using MATLAB with HTML, CSS, and JavaScript. I’m working on a small form where users can upload an image, and this image needs to be sent to MATLAB to be displayed using the imshow() function.

This is what I’m doing:

fig = uifigure("Position",[100 100 900 500]);
h = uihtml(fig,"Position",[0 0 900 500]);
h.HTMLSource = 'immagineInput.html';
h.HTMLEventReceivedFcn = @displayNumber;
function displayNumber(src,event)
name = event.HTMLEventName;
if strcmp(name,'ButtonClicked')
    number = event.HTMLEventData;
    b64 = matlab.net.base64decode(number);
    imshow(b64);
end
end

But the problem is that it displays an empty window, without the image.
The JavaScript code is the following:

function setup(htmlComponent) {
    var input = document.getElementById("immagine");
    var submit = document.getElementById("submit");
    submit.addEventListener("click", function () {
        var file = input.files[0];
        var reader = new FileReader();
        reader.onloadend = function () {
            htmlComponent.sendEventToMATLAB("ButtonClicked", reader.result);
        };
        reader.readAsDataURL(file);
    });
}

How to conceal the password the user enters from the backend dev

How to completely conceal the password that the user enters from the app maker ie Me;

So i am using bcryptjs to hash the password the user enters and store it to the database , so that the database admin cannot view the password , but i can easily see the password by just logging it to the console.

I thought , since bcrypt is a very popular package , i probably wont get anything if i logged req.body.password into the console.

screenshot_of_the_terminal

`const router = require(“express”).Router();
const User = require(“../models/user”);
const bcrypt = require(‘bcryptjs’);

router.post( “/register” , async (req,res) => {

var newUser = new User({
  username: req.body.username,
  email: req.body.email,
  password: req.body.password,
});

console.log(req.body.password);

var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync("B4c0//", salt);

var newUser = new User({
  username: req.body.username,
  email: req.body.email,
  password: hash,
});


try {

    const user = await newUser.save()

    res.status(200).json({
       user
    })
    
} catch (error) {

    console.log(error)
    
}

})

module.exports = router`