HTML input’s FileList is always empty even though the file was submitted [duplicate]

I am trying to retrieve some files that were submitted through a HTML form, but whenever I submit the file input, the FileList object I get back is always empty.

Here is the form code:

<form id="fileForm">
    <input type="file" id="fileInput" name="file" accept="images/*">
    <input type="submit">
</form>

and the javascript:

function getFiles() {
    const fileInput = document.getElementById("fileInput");
    console.log(fileInput.files);
}
document.getElementById("fileForm").addEventListener("onSubmit", getFiles());

this is what the console outputs after submitting my image file:

console output after submitting

Unable to delete (by setting a short expiry time) the cookie from BROWSER in Express

>What is the issue about:
I am unable to delete the cookie stored in my browser.

Although, I have tested the cookie deletion functionality in POSTMAN, and it works fine there.

>Things I have done to delete the cookie:

i) Send the cookie with random value and past expiry time

const cookieOptions={
            expires: new Date(Date.now()-10*1000), //setting the expiry date to past
            httpOnly:true,
        };
res.cookie("jwt","null",cookieOptions);

Here is the logout function for the logout route

//authController.js
exports.logout=async(req,res)=>{
    try{
        const cookieOptions={
            expires: new Date(Date.now()-10*1000),
            httpOnly:true,
        };
        console.log("Logging out");
        //res.clearCookie("jwt");                     //Have done this also
        res.cookie("jwt","null",cookieOptions);
        console.log("Deleted");
        res.status(200).json({
            status:"success",
            message:"Cookie has been deleted"
        });
    }catch(err){
        console.log(err);
        res.status(400).json({
            status:"failed",
            message: err.message
        })
    }
}

//userRoutes.js
router.route("/logout").get(authController.logout);
module.exports=router;

//app.js
const userRouter=require("./routes/userRouter")
app.use("/api/v1/users",userRouter);

Here is the login function through which user receives a cookie in browser stored as “jwt”

//authController.js
exports.login=async(req,res)=>{    
    try{
        const {email,password}=req.body;
        const user=await User.findOne({
            email:email
        }).select("+password");
        if(!user)
            throw `Please enter a valid email or password`;
        const correct=await user.compareNormalPwithHashedP(password,user.password);
        if(!correct) 
            throw `Please provide valid email or password`;   
        console.log(user);
        const token= jwt.sign({id:user._id,name:user.name},process.env.JWT_SECRET,{expiresIn:process.env.JWT_EXPIRES}); 
        const cookieOptions={
            expires:new Date(Date.now()+process.env.COOKIE_EXPIRES*24*60*60*1000),
            httpOnly:true
        }
        res.cookie("jwt",token,cookieOptions);
        res.status(200).json({
            status:"success",
            message:"You have logged in successfully",
            data:{
                user,
            }
        })
    }catch(err){
        console.log(err);
        res.status(400).json({
            status:"failed",
            message: err.message
        })
    }
}

ii) tried to await the res.cookie await res.cookie("jwt","null",cookieOptions);

iii) tried all sorts of experimentation with the expires such as:

i)const cookieOptions={
            expires: new Date(0),
            httpOnly:true,
        }
ii)const cookieOptions={
            expires: new Date(Date.now()),
            httpOnly:true,
        }
iii)const cookieOptions={
            expires: new Date(Date.now()+10*1000), //EVEN ADDING 10s EXPIRY TIME
            httpOnly:true,
        }

Still, that cookie sits there like a DUMB KID in the browser and is not moving at all or even modifying itself with the updated value and expiry time!!!

Here is my Frontend code in React from where its interacting with the Express server:

<div className="login-dropdown" onClick={async e=>{
    dispatch({type:"logout"});
    await axios.get("http://localhost:4001/api/v1/users/logout");
    navigation("/");
    window.location.reload();
}}>
   <div style={{display:"flex", marginLeft:"10px",position:"relative",top:"30%"}}>
      <img style={{width:"20px"}} src={logout_logo}/>
      <p style={{marginLeft:"20px"}}>Logout</p>
   </div>    
</div>

Is cookie deletion also not working in POSTMAN??

It is working PERFECTLY FINE when I am testing this in POSTMAN. No worries whatsoever. However, it is just not working in the browser. I have to manually delete the cookie from the browser for the logout functionality to actually work

PLEASE help me out as I am almost stuck for 5 hours straight with no solutions coming to the rescue from similar stackoverflow question with answers and in the internet…nothing is resolving this issue.
Please suggest what is going wrong in this piece of program.

Document.QuerySelector to fill a unique value with prepend and append

I am trying to use a JS code to fill up elements with their already filled up values as desribed in the table link image below:

enter image description here
For this code below, what modifcation will be required to get the desired final value?

var data = document.querySelectorAll("[id^='1253']").forEach(x => x.value
if( data > 0){
  var result = '(' + data + ')'
  document.querySelectorAll("[id^='1253']").forEach(x => x.value = result)
}

Use access token from first fetch in a second fetch API in React JS

As a newbie to React I have been stuck for awhile on how to get my access token to be put to use in a second fetch API. In the first fetch (Get token), I am able to successfully print my access token to the console. My issue is how to then use this token as the Bearer authorization in the second fetch (Get data). Any direction is appreciated.

App.js (with some private data redacted):

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      airData: []
    }
   }

componentDidMount(){

//Get token
var urlencoded = new URLSearchParams();
urlencoded.append("code", "MY_API_KEY");

var requestOptions = {
  method: 'POST',
  body: urlencoded,
  redirect: 'follow'
};

fetch("API_URL_FOR_TOKEN", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));



  //Get Data
  var myHeaders = new Headers();
      myHeaders.append("Authorization", "Bearer xxxxxxxxx");

      var urlencoded = new URLSearchParams();
      urlencoded.append("macAddress", "xxxxxxxxx");
      urlencoded.append("mode", "minute");

      var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: urlencoded,
      redirect: 'follow'
      };

  fetch("MAIN_API_URL", requestOptions)
   .then(response => response.json())
   .then(res => {
     console.log(res)
     this.setState({
       airData: res.data
     })
   });
  }


  
  render () {
        return (
          <div className="app">
             <header className="header">
                <div>
                <img src={logo} alt="Logo" className="logo" />
                    <div className="temperature">
                    
                        <FaTemperatureHigh /> 78°
                        
                    </div>
                </div>
            </header>
            <div className="spacer"></div>
            <OverallStatus />
            {this.state.airData.map(res => (
                  <div>
                    <div className='qualityFactor'>
                      <h1><img src={iconHumidity} alt="Logo" className="iconSmall" />Humidity <span className="right-justify">{res.humidity}%</span></h1>
                      <ProgressBar completed={res.humidity}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconAirPressure} alt="Logo" className="iconSmall" />Air Pressure <span className="right-justify">{res.airPressure} hPa</span></h1>
                      <ProgressBar completed={res.airPressure}
                      maxCompleted={1030} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonDioxide} alt="Logo" className="iconSmall" />Carbon Dioxide <span className="right-justify">{res.co2} ppm</span></h1>
                      <ProgressBar completed={res.co2}
                      maxCompleted={2000} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconVOCs} alt="Logo" className="iconSmall" />Chemicals <span className="right-justify">{res.tvoc} ppb</span></h1>
                      <ProgressBar completed={res.tvoc}
                      maxCompleted={1000} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconParticulateMatter} alt="Logo" className="iconSmall" />Particles <span className="right-justify">{res.pm25} ug/m3</span></h1>
                      <ProgressBar completed={res.pm25}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonMonoxide} alt="Logo" className="iconSmall" />Carbon Monoxide <span className="right-justify">{res.co} ppm</span></h1>
                      <ProgressBar completed={res.co}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconNitrogenDioxide} alt="Logo" className="iconSmall" />Nitrogen Dioxide <span className="right-justify">{res.no2} ppb</span></h1>
                      <ProgressBar completed={res.no2}
                      maxCompleted={200} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconOzone} alt="Logo" className="iconSmall" />Ozone <span className="right-justify">{res.ozone} ppb</span></h1>
                      <ProgressBar completed={res.ozone}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                  </div>
            ))}
          </div>
        )
    }
  }
  
  

export default App;

Why am I getting Uncaught TypeError: Td in Firebase?

I am implementing Firebase web API using Webpack and Express. My bundled webpack script file has been producing these strange errors:

Uncaught TypeError: Td is not a function
    at bundle.js:2:266675
    at bundle.js:2:273242
    at bundle.js:2:273246
bundle.js:2 Uncaught (in promise) ReferenceError: require is not defined
    at Object.566 (bundle.js:2:3803)
    at o (bundle.js:2:3931)
    at Function.o.t (bundle.js:2:4077)

Since this is happening in the bundle.js file, it is all on one line and difficult to read. However, I found the Td function referenced in bundle.js here:

var Td=Promise.resolve()
.then(o.t.bind(o,566,23)),
bd=o.e(846)
.then(o.t.bind(o,846,23)),
_d=Td();

...

I am deeply confused on what is causing this issue. I just did npm update on my directory. I was originally getting the same error but the function was labeled as “ld”, and then it changed to “Td” after updating. Could it be an error in Firebase’s recent release, or something else?

If anyone wanted to look at the source code, you can view it in the console on the site I’m publishing to:

https://milkywaymedium.com/

SVG graph and Javascript: Which is the best way to add animation to and SVG file?

I’m new at coding.

I’m studying the way to make an animated portfolio like Sean Halpin or Stephanie Walter one. I want to put a face, in which, blinking eyes and a moving the mouth would be the animated elements. Basically, I want to play with the visibility of the closed eyes and open mouth. As an example, I drew a face as follows:

<svg id="Capa_1" data-name="Capa 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 429 429"><defs><style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#000;stroke-miterlimit:10;}</style></defs><g id="face"><path class="cls-1" d="M611,608.5a214,214,0,1,1,151.32-62.68A212.6,212.6,0,0,1,611,608.5Z" transform="translate(-396.46 -180)"/><path d="M611,181a212.9,212.9,0,1,1-83.1,16.78A212.11,212.11,0,0,1,611,181m0-1c-118.46,0-214.5,96-214.5,214.5S492.5,609,611,609s214.5-96,214.5-214.5S729.43,180,611,180Z" transform="translate(-396.46 -180)"/></g><g id="eyes"><g id="eye_r"><circle class="cls-1" cx="319.15" cy="128.63" r="48.5"/><path d="M715.61,260.62a48,48,0,1,1-48,48,48.06,48.06,0,0,1,48-48m0-1a49,49,0,1,0,49,49,49,49,0,0,0-49-49Z" transform="translate(-396.46 -180)"/></g><g id="iris_r"><circle cx="319.15" cy="128.63" r="19"/></g><g id="eye_l"><circle class="cls-1" cx="109.85" cy="128.63" r="48.5"/><path d="M506.32,260.62a48,48,0,1,1-48,48,48.06,48.06,0,0,1,48-48m0-1a49,49,0,1,0,49,49,49,49,0,0,0-49-49Z" transform="translate(-396.46 -180)"/></g><g id="iris_l"><circle cx="109.85" cy="128.63" r="19"/></g><line id="closed_eye_l" class="cls-2" x1="62.04" y1="128.5" x2="158.04" y2="128.5"/><line id="closed_eye_r" class="cls-2" x1="270.69" y1="128.23" x2="366.69" y2="128.23"/></g><g id="closed_mouth"><ellipse cx="214.5" cy="309" rx="108.5" ry="11.5"/><path d="M611,478c29.08,0,56.41,1.25,77,3.51,30.68,3.38,31,7.32,31,7.49s-.35,4.11-31,7.49C667.37,498.75,640,500,611,500s-56.41-1.25-77-3.51c-30.69-3.38-31-7.32-31-7.49s.35-4.11,31-7.49c20.55-2.26,47.88-3.51,77-3.51m0-1c-60.2,0-109,5.37-109,12s48.8,12,109,12,109-5.37,109-12-48.8-12-109-12Z" transform="translate(-396.46 -180)"/></g></svg>

So, I thought three ways to do this:

  1. Place the svg inside an tag, calling then a function that takes into consideration the loading of the file. An example of what I’m saying is found in the following resource: https://www.petercollingridge.co.uk/tutorials/svg/interactive/javascript/, in the “External SVG + External JavaScript” part. It didn’t work. The contentDocument ALWAYS returns “null”.

In my example, it would be:

HTML:

<object id="face" data="path/to/face.svg" type="image/svg+xml"></object>

JS:

<script type="text/javascript">
  window.addEventListener("load", function() {
    var svgObject = document.getElementById('face').contentDocument;
    var svg = svgObject.getElementById('closed_eye_r');
    svg.style.visibility="hidden";
  });
</script>
  1. Inline SVG – call a “transform” property. Sean Halpin does it but I’m not sure what he does.

HTML: https://www.seanhalpin.design/
JS: https://www.seanhalpin.design/js/scripts.js

  1. Inline SVG, use getElementById and apply functions to animate the internal parts of the SVG file.

Questions:

a. Is Inline SVG a good practice?
b. Which is the best way to animate an SVG?

I hope to have been clear. Let me know if something is not well presented, I want to learn to edit questions in order to make them as clear as possible.

Thanks!

Creating a custom React Native component which automatically wraps inner text substrings with another component

I have the following component structure being rendered:

<Text>
 Hello <UsernameWrapper>@gaberocksall</UsernameWrapper>! Nice to meet you.
</Text>

I would like create a custom component which automatically places @usernames into a UsernameWrapper, like this (and it should be rendered identically to the above snippet):

<AutoUsernameText>Hello @gaberocksall! Nice to meet you.</AutoUsernameText>

Or, even more generally, something along the lines of:

<MagicWrapper wrap={/@w+/gi} wrapper={UsernameWrapper}>
  Hello @gaberocksall! Nice to meet you.
</MagicWrapper>

How would I go about creating the MagicWrapper component in React Native?

An image that has been replaced re-appears again if I click the upload window again

So I have this issue that I can’t seem to find a solution for. I have an ‘upload image’ area that’s part of my form. You’re allowed to either upload an image that has been downloaded on your computer or copy and paste an image address in the url, which should render the image in the image window. Everything works fine, except if:

  1. I upload a downloaded image from my computer downloaded-image

  2. I decide to instead copy an image url from the internet and use that instead image-from-internet

  3. The image from the internet appears and overwrites the old image

  4. I click on the image window again

  5. The old image reappears and overwrites my new image old-image

I’ve tried resetting the form control of the image window when the user clicks on it, but that ends up clearing the entire image window, discarding the image. How do I prevent the old image from overwriting my new image?

Generating an application access token using eBay RESTful APIs Error 401 grant type in request is not supported by authorization server

https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html

I am trying to generate an application access token in bubble.io but am getting hit with error 401 grant type in request is not supported by authorization server.

bubble api connector

bubble workflow

bubble workflow

When I preview my page, chrome developer tools displays the following error:


{&quot;error&quot;:&quot;unsupported_grant_type&quot;,&quot;error_description&quot;:&quot;grant type in request is not supported by the authorization server&quot;}

retrun values outside JS function

i have A map js function which let me to get the latitude and longitude from map,
however , I want to get those data outside the function in other variables to used again.

How Can I do It

map.on('click', function (e) {
    lat=e.latlng.lat;
    
          lon =  e.latlng.lng;
          
          document.getElementById('latitude').textContent = lat;
         document.getElementById('longitude').textContent = lon;

});
// console.log( lat,lat);

when I console ( lat,lat) it display to me that they are undefined

What is the correct approach on making a For Loop with a Cheerio Object?

Simply put, I’m scraping data from a website and storing it in a database.

The relevant fields are links, names, prices and item condition.

The way I’m handling this right now is to iterate through each Element and pushing them into their respective lists. Then adding it to a database with a For Loop. So, for example:

var names= [];
$(".midbox .framebox .frameboxcells .displaybox .displayboxbottom .dt.bg0 .serptablecell2-adv .serptablebasestyle2 .valtitle.lovewrap.padr4 .underlinedlinks").each(function(){
            names.push($(this).text());
        });
...
for (x in names){
                var sql = "REPLACE INTO `item` (`link`, `title`, `price`, `date`, `item_condition`, `country`) VALUES (?)";
                var values = [links[x], names[x], prices[x], '', states[x], cc];
            
                con.query(sql, [values], function(err, result){
                    if (err) throw err;
                    });
            }

This is very naive, as it hopes all Elements exist and that they align perfectly, which as worked well so far, until I’ve noticed some listings on the website I’m scraping do not have an Item Condition element, so it gets skipped and the lists get desynced, resulting in the wrong values being paired up.

I understand the answer I’m looking for has to do with the .each function, but I’m not exactly sure how to go about it. I suppose I have to go the highest point, it being .midbox .framebox .frameboxcells .displaybox .displayboxbottom .dt.bg0 .serptablecell2-adv .serptablebasestyle2 and go from there. Adding a NULL value if it doesn’t find an Element.

Below is the full (relevant) code:

const $ = c.load(response.data);

        $(".midbox .framebox .frameboxcells .displaybox .displayboxbottom .dt.bg0 .serptablecell2-adv .serptablebasestyle2 .splittable .splittablecell1 .padr2.bhserp-txt1.bhserp-new1").each(function(){
            var fixedStr = $(this).text().replace(/,|£|$|s|[(GBP)]|[(USD)]/g, '');
            prices.push(Number(fixedStr));
        });

        $(".midbox .framebox .frameboxcells .displaybox .displayboxbottom .dt.bg0 .serptablecell2-adv .serptablebasestyle2 .valtitle.lovewrap.padr4 .underlinedlinks").each(function(){
            names.push($(this).text());
        });

        $(".midbox .framebox .frameboxcells .displaybox .displayboxbottom .dt.bg0 .serptablecell2-adv .serptablebasestyle2 .splittable .splittablecell1.bhserp-txt1 .padl1.labinfo").each(function(){
            if ($(this)){
                states.push($(this).text());
            }
            else{
                console.log("Mistake here, pick me up!"); // I understand what I'm doing here does not make sense and is wrong as I've stated, but since that's what made me realize what I needed to do, I'm leaving it.
                states.push("None");
            }
        });

        $(".midbox .framebox .frameboxcells .displaybox .displayboxbottom .dt.bg0 .serptablecell2-adv .serptablebasestyle2 .valtitle.lovewrap.padr4 .underlinedlinks").each(function(){
            var tempLink = $(this).attr('href');
            var fixedLinks = tempLink.split("=");
            var fixedLinks = fixedLinks[1].split("&");
            links.push("https://www.ebay.co.uk/itm/" + fixedLinks[0]);
        });
...
con.connect(function(err){
            if (err) throw err;
            console.log("Connected!");
            for (x in names){
                var sql = "REPLACE INTO `item` (`link`, `title`, `price`, `date`, `item_condition`, `country`) VALUES (?)";
                var values = [links[x], names[x], prices[x], '', states[x], cc];
            
                con.query(sql, [values], function(err, result){
                    if (err) throw err;
                    });
            }
        });

How to handle nested files with FastAPI?

I’m working on a website where the frontend is done in React and the backend in Python with FastAPI. I made a form which takes a some data and sends it to the backend with axios. It looks like this

{
name='Jonathan',
aliases=["Johnny"],
birthdate='2-15-1980',
gender='male', 
height=178 
weight=90 
nationalities=["American", "French"], 
occupations=["Programmer", "Comedian"], 
status='single', 
images=[
  {'attachment': FileList,
   'location': 'Berlin',
   'date': '10-14-2019'
  }
]
}

However, when I submit it. FastApi seems to remove the images from the form.

name='Jonathan',
aliases=["Johnny"],
birthdate='2-15-1980',
gender='male', 
height=178 
weight=90 
nationalities=["American", "French"], 
occupations=["Programmer", "Comedian"], 
status='single', 
images=[
{'attachment': {'0': {}}, 'location': 'Berlin', 'date': '10-14-2019'}
]

This is what the route currently looks like

@router.post("/register/user")
def register_user(user_data: UserCreate):
    print(user_data)

I’m not entirely sure what’s going on. I’m guessing it has something to do with how the data is send and its encryption. I’m at a dead end here. Thanks in advance

I need to write a function where the product of two numbers need to equal 62 using JavaScript

So, I need to write a function that has two numbers and when multiplied equals 62.
This is what I have so far,

function multiply(){
  let a = 31
  let b = 2

  return a*b}

Now this is the test case that I need to pass

describe('multiply', function() {
 it("is an equation whose multiplied results will equal 62", function() {
  expect(num1).to.be.a('number')
  expect(num2).to.be.a('number')
  expect(multiply).to.eq(62)
});

I am not sure what I am doing wrong. I have tried different variations including Math.random() as well. Any help would be great.

VSCode formatting and autocomplete does not work as desired

I have a problem with my VSCode. The line from the widthImage downward remains unformatted. Autocompletion does not work from there downwards. This is really getting annoying. Restarting my IDE does not help either. This only happens when I use fragments <> </> or use the ? operator to check the object’s null state. Any help will be really appreciated. Thank you. Please find the attached screenshot below.enter image description here