Failed to fetch –

I have read How do I upload a file with the JS fetch API?

and

Getting “TypeError: Failed to fetch” when the request hasn’t actually failed

I have some javascript that sends a javascript object to WebApi backend, and it works!

I am now trying to use the same code to upload a file.

This is what I’m trying to upload to (my C# WebApi 2)

public async Task UploadImage([FromBody] object o)
{
    //do something
}

and the javascript

const file = inputTypeFile.files[0];

async function withData(url = '', data = {}, verb, success) {

const response = await fetch(url, {
     method: verb, 
     mode: 'cors', 
     cache: 'no-cache',
     credentials: 'same-origin', 
     headers: getHeader(),
     referrerPolicy: 'no-referrer', 
     body: file
 }).catch(function (e) {
     errorHandler(e);
 });

I always get a failure

Failed to fetch at withData

If I change the value of file to a valid json object, like {some:123} then it works fine.

Variable breaking script [closed]

If I add a vairable the bot message breaks.

This is the code I have right now

 await channel.send({
        embeds: [{
            color: categories.length > 0 ? CATEGORY_COLORS[categories[0]] : 0x0099ff,
            title: `${article.title} `,
            url: article.link,
            author: {
                icon_url: `attachment://image.png`,
                name: source
            },
            description: `${cleanDescription.substring(0, 250)}${cleanDescription.length > 250 ? '...' : ''}nn${categories.map(cat => `${cat}`).join(' | ')}nPing: <@&${GLOBAL_PING_ID}> ${categoryPings}n`,
            fields: embedFields,
            footer: {
                text: `Made by Genius74o`
            },
            image: {
                url: thumbnailUrl || '' 
            },
        }],
        files: [{
            attachment: `./images/image.png`
        }]
    });

But if i change image.png to a variable it breaksThis is the image without the vairable
This is the image with the varaible

It is the right parth to the image

Please help, thanks in advance

Webpack: Dynamically generate a file for file-loader that includes requires

I’m working with Webpack 4, and what I am trying to do is conceptually simple: I want to use file-loader with dynamically-generated content that can require other modules, instead of a static file.

In a little more detail, I want to:

  1. Generate an HTML page using Pug that requires a file dynamicfile.xml using file-loader. For example, the line link(name='search' href=require('./dynamicfile.xml')) should generate something like <link name="search" href="/dynamicfile.58ef.xml">, and a file dynamicfile.58ef.xml should be written to disk.
  2. The actual contents of dynamicfile.58ef.xml should be generated by a template or JS module, where part of it requires another module using file-loader. For example, if the template is in EJS syntax and looks like <sometag file="<%= require('./image.png') %> />", then the final contents of dynamicfile.58ef.xml should look something like <sometag file="/image.8a4e.png" />.

Note that I am using Webpack 4, not Webpack 5, because the project I am working with uses Webpack 4, and the migration to 5 would be very complicated and time-consuming.

I have already Googled and ChatGPT’ed the issue thoroughly and have not found a solution.

I tried generating the xml file dynamically with an EJS loader and then converting it to a string with apply-loader. In terms of the dynamically generated content, it gives my exactly what I want, if I require it inline in the HTML file. However, if I try to load it using file-loader in the HTML file, it always writes the source code of the template to the external xml file, instead of the dynamic content. So, I don’t understand why Webpack doesn’t evaluate the module’s code before writing it to the file (or how to do it). I think I have a conceptual misunderstanding that someone more knowledgeable can clear up for me.

I have also tried using val-loader@2, but it leads to exactly the same problem: file-loader writes out the source code generated by val-loader that would evaluate the module.

How to use an HTMLAudioElement controls to play the content of an AudioBuffer?

Considering the requirement of this function signature:

function initPlayer(player: HTMLAudioElement, buffer: AudioBuffer): void;

I’m looking for a way to control the AudioBuffer playback using the provided HTMLAudioElement.

I see plenty of examples using the start() method of a AudioBufferSourceNode, such as

const context = new AudioContext();
const destination = context.createMediaStreamDestination();
const source = context.createBufferSource();
source.buffer = buffer;  // some AudioBuffer instance
source.connect(destination);
source.start(0);

However this only plays the audio, it does not bind it to the player’s controls; play, pause, stop, seek, etc. have no effect.

There are also other solutions, using a Blob, or an ArrayBuffer from some downloaded mp3 file, for example. However the provided AudioBuffer is the only value I can work with, here.

I have looked at creating a audio/wav (or audio/mp3) Blob, but I can’t wrap my head around the idea that AudioBuffer can’t be directly played from a HTMLAudioElement.

Why is that, and what’s the proper solution to control the playback using the browser media player?

Script inside Template won’t execute on Import

I am learning about templates, custom elements, shadow DOM, etc. Here, I like to utilize Swiper lib to create custom element that i can compose as i wish in the future. It works when everything is one file as follows:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

  <template id="TmplCoverflowSwiper">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <style>
      html,
      body {
        position: relative;
        height: 100%;
      }

      body {
        background: #eee;
        font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
        font-size: 14px;
        color: #000;
        margin: 0;
        padding: 0;
      }

      .swiper {
        width: 100%;
        padding-top: 50px;
        padding-bottom: 50px;
      }

      .swiper-slide {
        background-position: center;
        background-size: cover;
        width: 300px;
        height: 300px;
      }

      .swiper-slide img {
        display: block;
        width: 100%;
      }
    </style>
    <div class="swiper mySwiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-7.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-8.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-9.jpg" />
        </div>
      </div>
      <div class="swiper-pagination"></div>
    </div>
    <script>
       (async () => {
          // <!-- Swiper JS -->
          const { Swiper } = await import("https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.mjs");
          console.log('swiper-bundle imported...')

          // <!-- Initialize Swiper -->
          var swiper = new Swiper(".mySwiper", {
            effect: "coverflow",
            grabCursor: true,
            centeredSlides: true,
            slidesPerView: "auto",
            coverflowEffect: {
              rotate: 50,
              stretch: 0,
              depth: 100,
              modifier: 1,
              slideShadows: true,
            },
            pagination: {
              el: ".swiper-pagination",
            },
          });

          console.log('swiper initiated...');
        }
        )();
    </script>
  </template>

  <script>
    class CoverflowSwiper extends HTMLElement {
      constructor() {
        super(); // always call super() first
      }

      /** Custom Component Reactions **/
      connectedCallback() {
        console.log("Coverflow-Swiper  connected to page");

        //set initial state of visiable
        this.visible = this.hasAttribute('visible');

        //make deep copy of the template and import into the current document
        let tmpl = document.querySelector("#TmplCoverflowSwiper");
        let newNode = document.importNode(tmpl.content, true);

        // document.getElementById("PCCoverflowSwiper").appendChild(newNode);
        this.appendChild(newNode);
      }
    }

    //link custom element w/ JS class
    customElements.define("pc-coverflow-swiper", CoverflowSwiper);
 
  </script>

</head>

<body>
  <h1>Making Swiper Web Component</h1>
  <pc-coverflow-swiper id="PCCoverflowSwiper">
  </pc-coverflow-swiper>
</body>
</html>

However, i like to keep things separate and when i move out all the code pertained to my custom element into a separate file that is imported in the main file, suddenly the JS script part of the template scope won’t execute and i cann’t seem to understand why it is so, just by removing into separate file?

The main file containing custom element tag while stripped out the rest into file tmpl-swiper.html and imported here in the head here:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

    <!-- include the polyfill for web components. This must precede imports -->
    <script src="../polyfills/webcomponents-lite.js"></script>

    <!-- import our template from an external file -->
    <link rel="import" href="tmpl-swiper.html" id="tmplCoverflow">
</head>

<body>
  <h1>Making Swiper Web Component</h1>
  <pc-coverflow-swiper id="PCCoverflowSwiper">
  </pc-coverflow-swiper>
</body>
</html>

Here is the imported template file taken out from the main file into separate file all pertained to the custom element with name tmpl-swiper.html:

html,
body {
position: relative;
height: 100%;
}

  body {
    background: #eee;
    font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #000;
    margin: 0;
    padding: 0;
  }

  .swiper {
    width: 100%;
    padding-top: 50px;
    padding-bottom: 50px;
  }

  .swiper-slide {
    background-position: center;
    background-size: cover;
    width: 300px;
    height: 300px;
  }

  .swiper-slide img {
    display: block;
    width: 100%;
  }
</style>
<div class="swiper mySwiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-7.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-8.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-9.jpg" />
    </div>
  </div>
  <div class="swiper-pagination"></div>
</div>
<script>
   (async () => {
      // <!-- Swiper JS -->
      const { Swiper } = await import("https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.mjs");
      console.log('swiper-bundle imported...')

      // <!-- Initialize Swiper -->
      var swiper = new Swiper(".mySwiper", {
        effect: "coverflow",
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: "auto",
        coverflowEffect: {
          rotate: 50,
          stretch: 0,
          depth: 100,
          modifier: 1,
          slideShadows: true,
        },
        pagination: {
          el: ".swiper-pagination",
        },
      });

      console.log('swiper initiated...');
    }
    )();
</script>

(function() {
class CoverflowSwiper extends HTMLElement {
constructor() {
super(); // always call super() first
}

  /** Custom Component Reactions **/
  connectedCallback() {
    console.log("Coverflow-Swiper  connected to page");

    //set initial state of visiable
    this.visible = this.hasAttribute('visible');

    //make deep copy of the template and import into the current document
    let tmpl = document.querySelector("#TmplCoverflowSwiper");
    let newNode = document.importNode(tmpl.content, true);

    // document.getElementById("PCCoverflowSwiper").appendChild(newNode);
    this.appendChild(newNode);
  }
}

//link custom element w/ JS class
customElements.define("pc-coverflow-swiper", CoverflowSwiper);

// automatically add the template 
//  to the document that is importing this file so it can be used.

// ownerDocument references this component document being imported
var thisImportDoc = document.currentScript.ownerDocument;

// Get the template from this file, clone it,
// and append it to the importing document.
var tmplNode = thisImportDoc.querySelector('#TmplCoverflowSwiper');

// the "document" keyword here references the "main" document
// (the one that's importing this HTML file)
document.body.appendChild(tmplNode.cloneNode(true));

})();

It imports the file, attaches the template, etc, however. the JS code within the Template tag isn’t executed and i can’t seem to understand the reason. Any help much appriciated. thank you

Why JS don’t show the last message in Telegram? [duplicate]

I am writing a chrome extension. I want to know the user’s last message in a telegram conversation. Here is my code:

js:

function getLastMessage() {
    const messages = document.querySelectorAll('.Message'); 

    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1];
        const messageText = lastMessage.querySelector('.text')?.innerText || "Нет текста";
        
        alert("Last message:", messageText);
 
    } else {
        alert("There are no messages");
    }
}
document.getElementById('myButton').addEventListener('click', function() {
    getLastMessage();
});

json:

{
    "manifest_version": 3,
    "name": "My Simple Button Extension",
    "version": "1.0",
    "description": "An extension with a single button.",
    "action": {
      "default_popup": "popup.html",
      "default_icon": "icon.webp"
    },
    "permissions": []
  }

This code alert “There are no messages” always but there are messages in chat.
Please, help me.

I can’t find anything in web

A way via functions to reverse the order of an array, using .sort() (need help explaining solution) [duplicate]

I’m new to javascript – I just had a problem that asked me to find a way via functions to reverse the order of an array of years, using .sort(). After flailing for a bit, I checked the answer and received the one below:

const sortYears = arr => arr.sort((x, y) => y - x);

I have no idea how someone would get this, or where the x and y come from.

I tried using sort() and nesting Collections.reverseOrder() as suggested in another answer to a similar question, but kept receiving errors.

Input type file – filelist, is always empty in partial view that is inside a partial view

I was able to get the filelist when the element was in the view > partialview1. But i had to change the interface a little bit so, it got moved to, View > partialview1 > partialview2. After this change, the filelist is always 0. What am i doing wrong? can anyone explain why this behaviour? I also tried setting timeout to the attachmentpartial js but it made no difference. Kindly guide.

Index controller

    public class ProjectDashboardController : Controller
    {
        public IActionResult Index()
        {
            try
            {
                ProjectListModel resultSet = _context.tblProjects.where(x => x.appid == 1).ToList();
                return View(resultSet);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        

        
        //get project list
        public IActionResult GetProjDetails(int projectid)
        {
            ProjecDetModel resultSet = _context.tblProjDetails.where(x => x.projectid == projectid).ToList();
            return View("~/Views/ProjectDashboard/_projDetails.cshtml", resultSet); //return partial view with object
        }
        
        public IActionResult GetAttachments(int pid){
            ProjAtt att = _context.tblProjAttachments.where(x => x.projectid = pid).ToList();
            return View("~/Views/ProjectDashboard/_AttachmentPartial.cshtml", att); //return partial view with object
            
        }
        
    }

Index page/view

    @model ProjectListModel

    <div class="form-group" style="display:flex;">
        <partial name="~/Views/Projs/_projList.cshtml" model="@Model" /> @* project list table *@
    </div>

_projList.cshtml

    @model ProjectListModel
    
    @foreach(var item in Model)
    {
        <a asp-controller="ProjectDashboard" asp-action="GetProjDetails" asp-route-projectid="@item.ProjectID">
            <i class="bi bi-search" title="View project details" onclick="showLoadingSpinner();"></i> @* project details page *@
            @item.ProjectName
        </a>
    }

_projDetails.cshtml

    @model ProjecDetModel
    //other code
    <div class="partialContent" id="AttachmentsContainerDiv" data-url="/APP/ProjectDashboard/GetAttachments?pid=1">
    </div>

_AttachmentPartial.cshtml

    @model ProjAtt

    <label class="bi bi-paperclip" onchange="fileAttached(@Model.ProjectID);">
        <input type="file" id="uploadFile" style="display: none;" multiple>
    </label>
    @foreach(var item in Model)
    {
        @item.attName
    }

site.js

    function fileAttached(pjid) {
        var files = document.getElementById('uploadFile').files; //get the attached files                        
        //THIS IS NOT WORKING
        console.log(files);
    }

BUT THIS IS WORKING

_projDetails.cshtml

    @model ProjecDetModel

    <label class="bi bi-paperclip" onchange="fileAttached(@Model.ProjectID);">
        <input type="file" id="uploadFile" style="display: none;" multiple>
    </label>
    
    
    //other code
    <div class="partialContent" id="AttachmentsContainerDiv" data-url="/APP/ProjectDashboard/GetAttachments?pid=1">
    </div>

_AttachmentPartial.cshtml

    @model ProjAtt

    @foreach(var item in Model)
    {
        @item.attName
    }

site.js

    
    $(document).on('change', '#uploadFile', function () {
        var file = $(this)[0]; // note the [0] to return the DOMElement from the jQuery object

        fileAttached(file.files);
        console.log(file.files[0]);
    });


    function fileAttached(files) {
        console.log(files); //THIS IS WORKING
    }

How to unify calendar timeslots in Javascript

I have a reservation calendar in my app that allows customers to make reservations in empty time slots. The calendar is also used by non-customer personnel who can make overlapping reservations in the calendar.

In order to avoid the customers from making overlapping reservations, I want to block out the overlaps in their view and only show single occurrances. The picture below shows what I am after:

calendar reservations

The left column shows the view of the personnel who can make overlapping reservations, the right view is what the customers should see. The customers are thus not allowed to make reservations in the smaller empty slots.

How can I achieve this with Javascript? I tried for loops which are comparing start and end times, but I ended up banging my head against the wall… And I am bound to solving this in the front-end, as I have no control over the back-end.

How to merge first column in html table using java script [closed]

I m using html table .I need to merge the row if rows have repeated values.
below is my code

function myFunction() {
  const previousRow = {};
  const colsChanged = {};
  let dark = false;

  Array.from(document.querySelectorAll('tbody tr')).forEach((tr, rowIdx) => {
    Array.from(tr.children).forEach((td, colIdx) => {
      if (rowIdx > 0 && previousRow[colIdx].text === td.innerText) {
        previousRow[colIdx].elem.setAttribute('rowspan', ++previousRow[colIdx].span);
        colsChanged[colIdx] = false;
        td.remove();

      } else {
        previousRow[colIdx] = {
          span: 1,
          text: td.innerText,
          elem: td,
          dark
        };
        colsChanged[colIdx] = true;
      }
    });
    const rowChanged = Object.values(colsChanged).every(Boolean);
    dark = rowChanged && rowIdx > 0 ? !dark : dark;
    if (dark) {
      // tr.classList.add('dark');
    }
  });
}
<body onload="myFunction()">
  <table class="table table-bordered" id="rejecteddetails" style="border-collapse: separate;empty-cells: hide;">
    <thead>
      <tr>
        <th class="text-center">
          S.No
        </th>
        <th class="text-center">Reason</th>
        <th class="text-center">Rejected By</th>
        <th style="white-space: nowrap;">Rejected Date</th>
        <th class="text-center">Response</th>
        <th class="text-center" style="white-space: nowrap;">Response Added By</th>
        <th class="text-center" style="white-space: nowrap;"> Response Added Date</th>
      </tr>
    </thead>
    <tbody id="rejected_reason_table">
      <tr>
        <td>1</td>
        <td>minimum thickness 25</td>
        <td>Testing</td>
        <td>2024-12-19 at 07:15 AM</td>
        <td>NA</td>
        <td>NA</td>
        <td>NA</td>
      </tr>
      <tr>
        <td>2</td>
        <td>wrong thickness value</td>
        <td>Test</td>
        <td>2024-12-18 at 11:12 PM</td>
        <td>corrected thickness. </td>
        <td>Test</td>
        <td>12-19-2024 at 12:53 AM</td>
      </tr>
      <tr>
        <td>3</td>
        <td>wrong thickness value</td>
        <td>Test</td>
        <td>2024-12-18 at 11:12 PM</td>
        <td>thickness value corrected and submitted . </td>
        <td>Test</td>
        <td>12-19-2024 at 02:02 AM</td>
      </tr>
      <tr>
        <td>4</td>
        <td>wrong thickness value</td>
        <td>Test</td>
        <td>2024-12-18 at 11:12 PM</td>
        <td>cannot update the value . value is static</td>
        <td>Test</td>
        <td>12-19-2024 at 06:59 AM</td>
      </tr>
    </tbody>
  </table>
</body>

Merging is working fine ,but I dont need to display 3, 4 in S.No column .I need to display only 2 because 2,3,4 are merged .

Javascript fetch return 403 on Apache Server

Struggling with this issue for a few days now so any help is greatly appreciated.

I managed to deploy my django project on a Linux server and it works fine apart from the model form submit. On the local development server it work fine and here is the workflow:

  1. User fills the form;
  2. User clicks submit;
  3. Javascript catches the submit event, submits a “POST” request and gets a response back;
  4. On the server side, the form is checked and if all is good an email is sent;
  5. HTML is updated to add the confirmation of form registration;

Here is my code:

home.html

    <div class="col-lg-8 offset-lg-2">
    <form method="POST" class="row mt-17" id="form" onsubmit="return false">
        {% csrf_token %}
        {% for field in form %}
        {% if field.name not in "message" %}
        <div class="col-12 col-sm-6">
            <div class=form-group>
                <label for={{field.name}} class="form-label">{{ field.label }}</label>
                {{ field }}
            </div>
        </div>
        {% else %}
        <div class="col-12">
            <div class=form-group>
                <label for={{field.name}} class="form-label">{{ field.label }}</label>
                {{ field }}
            </div>
        </div>
        {% endif %}
        {% endfor %}
        <div class="form-group mb-0">
            <button type="submit" class="btn btn-primary btn-lg">Submit</button>
        </div>
    </form>
</div>

main.js

const form = document.getElementById('form');
form.addEventListener("submit", submitHandler);
function submitHandler(e) {
    e.preventDefault();
    fetch("{% url 'messages-api' %}", {
        credentials: "include",
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new FormData(form)
    })
    .then(response => response.json())
    .then(data => {
        alert("Got your message")
        })

}

ssl.conf file

    <Directory /home/admin/pinpoint/templates>
            Require all granted
    </Directory>

    Alias /static /home/admin/pinpoint/static
    <Directory /home/admin/pinpoint/static>
            Require all granted
    </Directory>

    Alias /media /home/admin/pinpoint/media
    <Directory /home/admin/pinpoint/media>
            Require all granted
    </Directory>

    <Directory /home/admin/pinpoint/project>
            <Files wsgi.py>
                    Require all granted
            </Files>
    </Directory>

    WSGIScriptAlias / /home/admin/pinpoint/project/wsgi.py
    WSGIDaemonProcess pinpoint python-path=/home/admin/pinpoint python-home=/home/admin/pinpoint/venv
    WSGIProcessGroup pinpoint

On the development server, whenever you click submit, I get 403 (Forbidden) in the console.

Since the development version works fine, my guess would be it’s a permission issue. As such, I gave apache ownership and r+w rights in my templates folder. Still the issue persists.

If i remove the headers content in the fetch command, the form is registered in the database but after ~2 minutes I get Server Error(500).

Any help/suggestions are welcome.

API stops working on Express server side randomly

This is my server code:

import express from 'express';
import cors from 'cors';
import axios from 'axios';

const app = express()
const port = 3000;
app.use(cors());

app.get('/', async(req, res) => {
    await axios.get("<functional URL confirmed>")
        .then(response => {
            console.log(response.data);
        })
})

app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`);
});

The above code sometimes works perfectly and logs the data as expected. Most other times however, it outputs a very long error that looks something like this:

Error Screenshots:

enter image description here

enter image description here

Changed absolutely NOTHING in my code, just re-ran after a minute or so, and:

enter image description here

What I have already tried to solve this:

  • Checked my internet connection and speed. Everything is a-ok.
  • Checked my API quota. I am not violating it. I know because I can npm run dev my frontend which uses that api with the same url and output the same data with no errors even while I see this error on the backend
  • Checked the URL. I know it’s correct because of the same reason as above.
  • Tried waiting for a minute before re-running the same code. It worked. Then I ran it again. Didn’t work.
  • Assumed it was a time limit thing. Wrong. Waited for 15 minutes before re-running, still didn’t work.
  • Cut and pasted the same URL again just to change something. Data logged successfully.
  • Re-ran the code. Error again.

I don’t know what’s causing this erratic behaviour.

In case anyone wonders why I’m even using an Express server when the API can be called directly in my React frontend, it’s because this preliminary call isn’t causing issues but some other stuff on the same URL is giving me CORS errors. However the url I’m using here to test my server-side code is the same one that is definitely functional in the frontend.

Can someone please explain what is going on behind the scenes?

NPM Errors when trying to run scripts

Whenever I try to install an NPM module or run scripts I get several error messages

When I enter npm run dev I get this message:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /home/hc/northcoders/projects/exhibition-curation-platform/package.json
npm ERR! errno -2
npm ERR! enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/hc/northcoders/projects/exhibition-curation-platform/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in: /home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-debug-0.log

here’s the log file:

0 verbose cli /home/hc/.nvm/versions/node/v21.6.2/bin/node /home/hc/.nvm/versions/node/v21.6.2/bin/npm
1 info using [email protected]
2 info using [email protected]
3 timing npm:load:whichnode Completed in 1ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/npmrc Completed in 1ms
6 timing config:load:builtin Completed in 1ms
7 timing config:load:cli Completed in 1ms
8 timing config:load:env Completed in 0ms
9 timing config:load:file:/home/hc/northcoders/projects/exhibition-curation-platform/.npmrc Completed in 0ms
10 timing config:load:project Completed in 1ms
11 timing config:load:file:/home/hc/.npmrc Completed in 0ms
12 timing config:load:user Completed in 0ms
13 timing config:load:file:/home/hc/.nvm/versions/node/v21.6.2/etc/npmrc Completed in 0ms
14 timing config:load:global Completed in 0ms
15 timing config:load:setEnvs Completed in 0ms
16 timing config:load Completed in 5ms
17 timing npm:load:configload Completed in 5ms
18 timing config:load:flatten Completed in 1ms
19 timing npm:load:mkdirpcache Completed in 0ms
20 timing npm:load:mkdirplogs Completed in 1ms
21 verbose title npm run dev
22 verbose argv "run" "dev"
23 timing npm:load:setTitle Completed in 1ms
24 timing npm:load:display Completed in 0ms
25 verbose logfile logs-max:10 dir:/home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-
26 verbose logfile /home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-debug-0.log
27 timing npm:load:logFile Completed in 17ms
28 timing npm:load:timers Completed in 0ms
29 timing npm:load:configScope Completed in 0ms
30 timing npm:load Completed in 35ms
31 timing command:run Completed in 1ms
32 verbose stack Error: Could not read package.json: Error: ENOENT: no such file or directory, open '/home/hc/northcoders/projects/exhibition-curation-platform/package.json'
32 verbose stack     at async open (node:internal/fs/promises:633:25)
32 verbose stack     at async readFile (node:internal/fs/promises:1242:14)
32 verbose stack     at async PackageJson.load (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/node_modules/@npmcli/package-json/lib/index.js:129:31)
32 verbose stack     at async PackageJson.normalize (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/node_modules/@npmcli/package-json/lib/index.js:115:5)
32 verbose stack     at async RunScript.run (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/lib/commands/run-script.js:72:27)
32 verbose stack     at async module.exports (/home/hc/.nvm/versions/node/v21.6.2/lib/node_modules/npm/lib/cli-entry.js:61:5)
33 verbose cwd /home/hc/northcoders/projects/exhibition-curation-platform
34 verbose Linux 6.8.0-49-generic
35 verbose node v21.6.2
36 verbose npm  v10.2.4
37 error code ENOENT
38 error syscall open
39 error path /home/hc/northcoders/projects/exhibition-curation-platform/package.json
40 error errno -2
41 error enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/hc/northcoders/projects/exhibition-curation-platform/package.json'
42 error enoent This is related to npm not being able to find a file.
42 error enoent
43 verbose exit -2
44 timing npm Completed in 76ms
45 verbose code -2
46 error A complete log of this run can be found in: /home/hc/.npm/_logs/2024-12-20T15_26_19_111Z-debug-0.log

Fairly sure this only started happening after following some instructions online to fix a bluetooth problem on my laptop – had no idea what I was doing

running Node 10.2.4 on Ubuntu 22.04

Any help would be much appreciated,

Thanks

I am making a password checker for an admin login page it doesn’t when it should on paper [closed]

So I am making a login page for my website for admins and it has just one set password and it worked but when I tried to check if it would kick me out and it just sends me to the Admin page and not asking me for a password

this is my code:

</head>
    <body>
        <h1>This is Admin only</h1>
        <form id="password">
            <input type="password" name="Admin password" id="ADMIN_PASS">
        </form>
        <script>
            var password = "password"
            if (password = "ADMINPASS"){
                var password = 0
                location.href='ADMIN.html'
            }else{
                print('incorrect')
                location.href='Adminlogin.html'
            }
            

            
        </script>