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>

MutationObserver() vs DOMNodeInserted [duplicate]

I’m having trouble wrapping my head around MutationObserver(). I have an old snippet using DOMNodeInserted which has been depreciated.

The following is a scaled down illustration.

Example

       var d = $(document);

       // DOM Injection/Addition
       d.on('DOMNodeInserted', '*', function (e) {
           $('.ct-cont'    , e.target).addClass('bg-light m-0 p-0 w-100')
           $('.fa-solid'   , e.target).addClass('fa-fw')
           $('.ct-input'   , e.target).css('font-family', 'Courier New');
           return false;
       });

Any assistance would be appreciated and rewarded.

js multistep onboarding fail b/c CSRF token

I purchased a well known nice admin UI for an app i’m building in Rails so that I can focus on building instead of UI which is not my strong suit. This app requires multistage onboarding. What I discovered is that everything is being thrown off by the CSRF token Rails inserts into forms, a hidden input tag and it just feels insane. While I am competent in many programming languages I have had bubonic avoidance for js. The UI team has decided I should disable CSRF for registration which seems stupid to me.

the CSRF token looks something like this:

<input type="hidden" name="authenticity_token" value="LilF6KgbBR7MBSruMcWFKyMOz_pnmcGzmiyxAm2aVDIvurHbA_uxcOqVNfB4NZbKPc7KzDoD8MGWpJAh7ErcDQ" autocomplete="off" />

The steps are wrapped by the form that roughly looks like the below and the js refreshes the UI to cycle through onboarding stages the view is roughly like this, trying my best to abbreviate it, mixing html and erb because this is a js issues:

<form class="my-auto pb-5" novalidate="novalidate" id="kt_create_account_form">
     <input type="hidden" name="authenticity_token" value="LilF6KgbBR7MBSruMcWFKyMOz_pnmcGzmiyxAm2aVDIvurHbA_uxcOqVNfB4NZbKPc7KzDoD8MGWpJAh7ErcDQ" autocomplete="off" />
     <%= render "reg_step1" %>
     <%= render "reg_step2" %>
     <%= render "reg_step3" %>
     <%= render "reg_step4" %>
     <%= render "reg_step5" %>
     <%= render "registration_actions" %>
</form>

The partials are basically divs wrapping the onboarding steps with a class marking the content for each step. That are queried by js in the following way:

var el = parent.querySelectorAll('[data-stepper-element="content"]');

and then the UI is refreshed based on the step.

I had hoped that I could filter out the one input tag so that it doesn’t break the the multistage registration, because even when I test this as just pure html and js, that one input tag messes everything up.

I tried to do the following:

[...parent.querySelectorAll(query)]
                    .filter(function(element) {
                        return element.name !== 'authenticity_token' && element.type !== 'hidden';
                    });

to no avail. Is there anything obvious from this so far? How on earth is this one CSRF input tag which is before the queries divs wreaking complete havoc like this? Help would be greatly appreciated.

WordPress Elementor Pro Gallery not loading images – Bundle webpack file versions are different?

In WordPress, Elementor Pro, I have a Gallery. The photos suddenly stopped showing.

From the JS Console it shows:

Uncaught (in promise) ChunkLoadError: Loading chunk gallery failed.

In the folder wp-content/plugins/elementor-pro/assets/js:

There is a file: gallery.805130d33e18cb04635f.bundle.js

But server is asking for gallery.b7d55bc976e04f751975.bundle.js

Is this a webpack issue? How do I resolve this please?

I tried clearing the cache, and Elementor Regenerate CSS and data, but no luck so far.

I did reinstall a plugin this morning: Powerpack Lite for Elementor

Any ideas on how to solve this?

Calling other script to post after other funcation

I want to call other script to start running every 1 second after the first one is called,

but am having a problem the above script doesn’t report any error in browser and its not working. it only do post call to first function.

but doesn’t call other one after is called

I want the first call to do post after then call other one to also do a post call, run every 1 second or call file2 every 1 second

and then when it reaches 5min do not do any post call on file2(stop calling)

<script>
            function Fun_1() {
                ("#MkB").click(function (event) {
                    Execute();
                });

                function Execute() {
                    .ajax({
                        type: "POST",
                        url: "file",
                        data: {
                            
                            textnum: ("input[name='textnum']").val(),
                           
                        },

                        beforeSend: function () {
                            if (("form input[name='textnum']").val() == "") {
                                ("#error").text("action needed.");
                                return false;
                            }
                            
                        },

                        complete: function () {
                            ("#error").hide();
                            
                        },

                        success: function (response) {
                            myVa = setTimeout(() => {
                                clearTimeout(myVar);
                            }, 300000);
                            setTimeout(Fun_2, 3000);
                        },
                        error: function () {
                            alert("Something has Happened");
                        },
                    });
                }
            }

            function Fun_2() {
                myVar = setTimeout(Fun_2, 1000);
                timeout: 300000,
                .ajax({
                    type: "POST",
                    url: "file2",                    
                    success: function (res) {
                         var Rmsg = res.msgEnd;
                        ("#FeMsg_1").html(res.msg);
                        
                        if (Rmsg == 'Complete') {
                         clearTimeout(myVar);
                         clearTimeout(myVa);
                    },
                });
            }

            (document).ready(function () {
                Fun_1();
            });
        </script>

How to bulk upload and edit metadata of each file in NodeJS?

I’m trying to test something in my NodeJS app in Postman where I want to be able to upload files. Now, the uploading itself works fine and I can just pass bunch of files in the multipart/form-data:

 async upload(req: Request, res: Response): Promise<void> {
    try {
      const user = await req.getUser();
      const { isAdmin, orgId, type: fileType, isLogo, isIcon } = req.query;

      const name = user.fullName;
      const altText = req.query.altText as string;
      const isAdminBool = util.toBool(isAdmin as string | undefined);
      const isLogoBool = util.toBool(isLogo as string | undefined);
      const isIconBool = util.toBool(isIcon as string | undefined);
  
      // Resolve destination folder based on conditions
      const destFolder = isAdminBool
        ? 'files/admin'
        : orgId
        ? `files/organization/${orgId}`
        : `files/user/${user.id}`;
  
      // Get files from the request
      const files = req.files as Express.Multer.File[];
  
      // Create a list of promises to handle file uploads
      const promUploads = files.map(async (file) => {
        const origname = file.originalname;
        let filename = origname;
  
        // Rename filename for icons
        if (fileType === 'icon') {
          const ext = path.extname(origname);
          if (!origname.endsWith(`.ico${ext}`)) {
            filename = `${path.basename(origname, ext)}.ico${ext}`;
          }
        }
  
        await this.storageService.isExists({ ...file, originalname: filename }, user.azure_id);
  
        return this.storageService.copyAndUploadFile(file.path, {
          delete: true,
          renameFilepath: `${destFolder}/${filename}`,
          category: fileType as string | undefined,
          uploadedBy: `${user.firstname} ${user.lastname}`,
          isIcon: isIconBool,
          isLogo: isLogoBool,
          title: name,
          altText
        });
      });
  
      const result = await Promise.all(promUploads);
  
      res.jsonSuccess(result);
    } catch (error) {
      console.error('Error uploading images:', error);
      res.jsonError({ message: 'Failed to upload images', error });
    }
  }

What I need to be able to do now is that I want to be able to edit the properties of each file as I upload them. So if I have 5 files being uploaded, I want to be able to edit the name, altText, isLogo and isIcon independently.

So suppose I have 5 images being uploaded at the same time. I’d like to be able to change the metadata etc of all those 5 images.

Any guidance or assistance on how I can do this?

Organizing code for interdependent modules

Purpose: I’m writing a JS library that will consist of a core class which will be extended by submodules. Those submodules need to be able to plug independently on this core and have access to a few utilities imported by the core (api endpoints and functions, l10n strings and methods, …).

As each component is executed, data is progressively added to the this of the subclass (thus the one of the main class), and I’d like every utility to have access to that this dynamically so it always has the latest version of the variables attached to it.
This is why I can’t call utility classes with a parameter (this.apis = new Apis(this) will create a copy of this at the moment of instanciation but not update it afterwards).

I have thought of Proxies, but it doesn’t seem to be relevant in that case. So far, the best I have found to do -and that works- is by using any_method.bind(this). However, I don’t know how to bind a full class so that all the methods will have access to this and not have to bind each method separately.

Would anyone have any suggestion for a clean reactive system for my use case?
If not, maybe anyone can tell me how to bind(this) a whole class?

Thanks a lot

JavaScript Weather Widget is being invoked twice despite seeing only one function call in the console

My JavaScript Weather Widget is fetching live weather warnings via the Met Office website’s RSS feed. The problem is that the warnings display twice on the page, so I think there must be duplicate call to the fetch function that I can’t find. The weather-widget.js script is only included once on the page. I have run a stack trace and the console shows only one call, so I can’t work out why the warning is being displayed twice. I am using axios for the http request and Bootstrap 5 to display the warnings.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Widget</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="card shadow-lg">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Weather Warnings</h5>
            </div>
            <div class="card-body">
                <div id="weather-widget">
                    <p>Loading weather warnings...</p>
                </div>
            </div>
        </div>
    </div>
    <script src="weather-widget.js"></script>
</body>
</html>

weather-widget.js

document.addEventListener("DOMContentLoaded", function () {
    const widgetContainer = document.getElementById("weather-widget");
    const rssFeedUrl = "https://corsproxy.io/https://www.metoffice.gov.uk/public/data/PWSCache/WarningsRSS/Region/yh";

    // Fetch and parse the RSS feed
    async function fetchWeatherWarnings() {
        console.trace("fetchWeatherWarnings() trace");
        try {
            const response = await axios.get(rssFeedUrl, {
                headers: {
                    'Accept': 'application/rss+xml'
                }
            });

            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(response.data, "application/xml");

            // Extract warning items
            const items = xmlDoc.querySelectorAll("item");
            if (items.length === 0) {
                widgetContainer.innerHTML = "<p>No weather warnings available at the moment.</p>";
                return;
            }

            // Generate HTML for warnings
            let warningsHtml = "";
            items.forEach((item) => {
                const title = item.querySelector("title").textContent;
                const link = item.querySelector("link").textContent;
                const description = item.querySelector("description").textContent;
                const enclosure = item.querySelector("enclosure")?.getAttribute("url");

                warningsHtml += `
                    <div class="mb-3">
                        <h6 class="fw-bold">${title}</h6>
                        <p>${description}</p>
                        ${enclosure ? `<img src="${enclosure}" alt="Warning icon" class="img-fluid mb-2">` : ""}
                        <a href="${link}" target="_blank" class="btn btn-sm btn-outline-primary">Read More</a>
                    </div>
                    <hr>
                `;
            });

            widgetContainer.innerHTML = warningsHtml;
        } catch (error) {
            console.error("Error fetching weather warnings:", error);
            widgetContainer.innerHTML = "<p>Unable to load weather warnings. Please try again later.</p>";
        }
    }

    // Fetch warnings on load
    fetchWeatherWarnings(console.log("Script executed"));
});

How can I extend the (default) timeout generated by window.open() if page takes longer?

Inside own javascript code I need to open a popup using window.open(url).
Unfortunately serving url is taking longer than the javascript implementation of this open.window() function is set to wait (as default) for a url and it generates a timeout saying that “the connection is broken”.

Instead, serving thie url takes simply longer than this 30 seconds. The server is serving (because I know that, it is my server).

I am using javascript of the hosting browser, an updated firefox or chrome on android.

Window.open() is a very practical function. Instead of that I would have to implement an own popup opening function using Ajax primitives. I would prefer to stay with that window.open() function if there were a possibility.

Is there a way to modify this (hidden?) timeout for window.open() in order for this function to wait longer for the url given to it? e.g. 90 seconds or longer? I do not want to see “connection broken” I would like rather this function to wait longer than the default.

Thanks a lot in advance!