Vite Rails and JS modules in views

I was working on migrating from webpacker to vite and it has been pretty seemless overall, just have one question in regards to using imported JS in a view.

Currently have an entrypoint — lets just say it looks like this:

import { testMethod } from '~/src/js/testfunctions.js'
import '~/src/css/test.scss'
etc...

The js file structure is like this:

export function testMethod() {
  ..code here
}

And in my view, I have a script tag at the bottom of the file, trying to call my method:

%script{type: 'module'}
  :plain
    testMethod();

but the method is unavailable to call from the view for whatever reason — testMethod() is not defined error in the console.

Telegram Story post from a Telegram miniapp

Telegram Story post from a Telegram miniapp with a predefined image and caption, which preloads waiting for a user to post the preloaded media using javascript or deeplink

A javascript code of the solution or deeplink. A button link is suppose to call and load these images and caption on a user’s story with for user to post

I have this error when I npm start my react project. anyone able to solve this?

I have this error when I npm start my react project. anyone able to solve this? I’ve installed and uninstalled node_modules and the same error remains.

./src/app/App.scss (./node_modules/css-loader/dist/cjs.js??ref–6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref–6-oneOf-5-3!./node_modules/sass-loader/lib/loader.js??ref–6-oneOf-5-4!./src/app/App.scss)

padding: $modal-inner-padding – $modal-footer-margin-between * .5; ^ Incompatible units: ‘rem’ and ‘px’.

in /home/falcao/squad-app/node_modules/bootstrap/scss/_modal.scss (line 178, column 12)

What colour notations does Plotly.js support?

I’m trying to plot a bar chart, with bars of a specific colour, using Plotly 1.47.4:

Plotly.newPlot(plotElement,
               [{
                   type: "bar",
                   x: ["A", "B", "C"],
                   y: [1, 2, 3],
                   marker: {color: "red"}
               }]);

For the marker colour, i can use named CSS colours, and traditional CSS #rrggbb notation, and more modern CSS rgb(r g b) and hsl(h s% l%) notation. But modern CSS oklch(l% c h) and hwb(h w% b%) don’t seem to work – i get default blue bars.

If i inspect the generated SVG, i see what however i specify the colour in the newPlot call, the path element constituting the bar has a fill colour defined in rgb(r, g, b) format.

So, it seems Plotly is parsing the marker colour value, and translating it to RGB itself.

What notations does Plotly support here? Is there a plan to support the newer ones?

Including specific parts of lib.dom in a Typescript project

I have a Typescript project that runs in a limited environment that includes React but does not allow access to many common Window features. For example AudioBuffer is not something users have access to (or want to use) and I do not want it showing up in intellisense autocomplete.

  "compilerOptions": {
    // DOM is required for React but includes _a lot_ of types
    "lib": ["ES2022", "DOM"],

I’d like to expose specific parts of Window (e.g. console and URLSearchParams) with something like this:

// pseudocode!
declare type global = Pick<lib.dom, "console" | "URLSearchParams"> 

The result is that users would see types for console and URLSearchParams types but AudioBuffer and friends included in the rest of the lib.dom definition.

Jest Test with Vue3 – $q.loading is undefined

Currently migrating a project from Vue2 to Vue3, and it’s mostly done – the app seems to work fine. However, Jest tests seem to have trouble passing. I have updated Vue Test Utils to V2 for Vue3 compatibility.

This is the error:

...Request.vue:67412
              _this4.$q.loading.hide();
                                ^

TypeError: Cannot read properties of undefined (reading 'hide')
    at hide (...Request.vue:530:33)
    at tryCatch ([email protected]:45:16)
    at Generator.<anonymous> ([email protected]:133:17)
    at Generator.next ([email protected]:74:21)
    at asyncGeneratorStep ([email protected]:3:17)
    at _next ([email protected]:17:9)

Unfortunately, the line numbers do not line up with what is described (i.e., Request.vue is really only ~10k lines, and line 530 does not actually have hide called).

After a bit of investigation, this is the line:

this.$q.loading.hide();

Called directly in Request.vue (i.e., not called from an imported function or anything). Again, confusingly, this is not an issue when actually running the application, and the loading screen hides just fine. Disabling this line causes the loading screen to stay forever, expectedly.

I have included this line at the top of the jest test file:

import { installQuasarPlugin } from '@quasar/quasar-app-extension-testing-unit-jest';

installQuasarPlugin();

As per instructions for testing quasar related items in Vue3.

Following is the package.json for relevant items:

"dependencies": {
...
    "quasar": "^2.16.4",
...
},
"devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/eslint-parser": "^7.13.14",
    "@quasar/app-webpack": "^3.13.2",
    "@quasar/quasar-app-extension-testing": "^2.0.6",
    "@quasar/quasar-app-extension-testing-e2e-cypress": "^5.2.0",
    "@quasar/quasar-app-extension-testing-unit-jest": "^3.0.3",
    "@vue/compiler-sfc": "^3.4.27",
    "@vue/test-utils": "^2.4.6",
    "@vue/vue3-jest": "^29.2.6",
    "audit-ci": "^3.0.0",
    "babel-jest": "^29.7.0",
    "cypress": "^13.2.0",
    "cypress-ntlm-auth": "^4.2.0",
    "eslint": "^8.11.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-plugin-cypress": "^2.2.1",
    "eslint-plugin-vue": "^9.0.0",
    "eslint-webpack-plugin": "^4.1.0",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "webpack-cli": "^5.1.4"
},

Note that I also tried doing $q.loading.show() in front of $q.load.hide() just in case it was some weird quirk, but I suppose unsurprisingly, it causes the same error.

I’m hesitant to do:

$q.loading?.hide()

Just to get the test to pass, as I feel like this’ll have unexpected side effects in the actual application.

Any help is appreciated. Thanks!

Free file hosting with permanent direct link [closed]

I need a free site/server where I can host my files, files that my electron app needs to download. I have searched for information and tried alternatives and none of them meet the requirements I need:

  • Permanent direct link
  • No “cors” restrictions
  • Allow files of at least 1gb

If anyone knows of any alternative, whatever it may be, as long as it’s free, please let me know. Thanks!

I have tried alternatives such as Google Drive, which ends up blocking the file because it cannot be scanned for viruses as it is a large file, Mediafire does not have a permanent link, OneDrive and Github give me “cors” problems as well…

Each tag is run twice

I’m just starting in blazer, trying to write a webpage with wasm. I was having trouble including 3rd party javascript libraries (it seemed like they were getting run twice) and I’ve simplified the issue to this simple example. Here is the entire content of Map.razor:

@page "/map"
@rendermode InteractiveWebAssembly

<script>
    console.log("starting");
    const myConstant = 2;
</script>

When I run this and navigate to https://localhost:7028/map in my browser, I get an error in the console: “Uncaught SyntaxError: redeclaration of const myConstant”. I’ve looked at the page-source in the browser and confirmed that there is only one instance of this script tag. I thought the behavior could be re-rendering related so I added some debugging code:

@page "/map"
@rendermode InteractiveWebAssembly

<script>
    console.log("starting");
    const myConstant2 = 1;
</script>


@code {
    protected override async Task OnInitializedAsync()
    {
        Console.WriteLine("Initialized");
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        Console.WriteLine("rendereding");
    }
}

And the output is as I expect (only says “Initialized”, “rendereding”, and “starting” once). If I change my tags to reference a source file instead of having the javascript inline, the network tab in the browser developer window shows that the script is being fetched twice, once at the beginning, and then again after a half-second delay. And it still gets run twice (error on constant being already defined, or repeats of console.log messages).

@page "/map"
@rendermode InteractiveWebAssembly

<script src="/js/MapBehavior.js"></script>

@code {
    protected override async Task OnInitializedAsync()
    {
        Console.WriteLine("Initialized");
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        Console.WriteLine("rendereding");
    }
}

Where MapBehavior.js has:

console.log("loading MapBehavior.js");
const myConstant = 1;
console.log("defined constant in MapBehavior.js");
console.log("loaded mapBehavior.js");

And the console output is:

loading MapBehavior.js MapBehavior.js:7:9
defined constant in MapBehavior.js MapBehavior.js:9:9
loaded mapBehavior.js MapBehavior.js:401:9
CSS Hot Reload ignoring https://localhost:7028/bootstrap/bootstrap.min.css because it was inaccessible or had more than 7000 rules. browserLink:50:1248
dotnet Loaded 8.50 MB resources
This application was built with linking (tree shaking) disabled. 
Published applications will be significantly smaller if you install wasm-tools workload. 
See also https://aka.ms/dotnet-wasm-features assetsCache.ts:30:12
Debugging hotkey: Shift+Alt+D (when application has focus) blazor.web.js:1:154576
Initialized blazor.web.js:1:157717
rendereding blazor.web.js:1:157717
Uncaught SyntaxError: redeclaration of const myConstant
    <anonymous> https://localhost:7028/js/MapBehavior.js:1

I’ve seen this issue with firefox, chrome, and edge. I’ve done a fresh install of VisualStudio but maybe it saved some errant setting from a previous install. I’ve disabled hot-reload during debugging, no effect.

Why are my script tags being run twice by browsers?

ERR_MODULE_NOT_FOUND when building TypeScript project with ESNext features

I’m trying to build a TypeScript project using the latest ESNext features, but I’m encountering an ERR_MODULE_NOT_FOUND error when I run my application. Below are the details of my setup and the error message I receive.

Project Structure

/api
├── package.json
├── tsconfig.json
├── index.ts
└── server.ts

package.json

{
    "name": "api",
    "version": "1.0.0",
    "main": "index.js",
    "type": "module",
    "scripts": {
        "build": "tsc",
        "start": "node index.js"
    },
    "dependencies": {
        "express": "5.0.0"
    },
    "devDependencies": {
        "@types/express": "^4.17.21",
        "@types/node": "^20.16.11",
        "typescript": "^5.6.2"
    },
    "sideEffects": false,
    "engines": {
        "node": ">=18"
    }
}

tsconfig.json

{
    "compilerOptions": {
        "lib": [
            "es2023"
        ],
        "target": "ESNext",
        "module": "ESNext",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "jsx": "preserve",
        "importHelpers": true,
        "alwaysStrict": true,
        "strict": true,
        "useUnknownInCatchVariables": true,
        "strictFunctionTypes": true,
        "allowUnusedLabels": false,
        "allowUnreachableCode": false,
        "exactOptionalPropertyTypes": true,
        "noImplicitOverride": true,
        "allowJs": true,
        "sourceMap": true,
        "skipLibCheck": true,
        "suppressExcessPropertyErrors": false,
        "noImplicitUseStrict": false,
        "suppressImplicitAnyIndexErrors": false,
        "noStrictGenericChecks": false,
        "forceConsistentCasingInFileNames": true,
        "noUncheckedIndexedAccess": true,
        "isolatedModules": true,
        "noFallthroughCasesInSwitch": true,
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "strictBindCallApply": true,
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "strictPropertyInitialization": true,
        "noPropertyAccessFromIndexSignature": false,
        "declaration": true,
        "outDir": ".",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "esModuleInterop": true,
        "resolveJsonModule": true
    },
    "exclude": [
        "node_modules",
    ],
    "typeRoots": [
        "node_modules/@types"
    ],
    "types": [
        "node",
        "express"
    ]
}

index.ts

import "./server";

server.ts

import express from "express";

const app = express();
const port = 3000;

app.get("/", (_req, res) => {
  res.status(200).json({ message: "Hello World" });
});

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

Run Commands

npm i
npm run build
npm run start

Error Output

> [email protected] start
> node index.js

node:internal/process/esm_loader:40
      internalBinding('errors').triggerUncaughtException(
est-tsserver' imported from ..index.js
Did you mean to import ../server.js?
    at new NodeError (node:internal/errors:405:5)
    at finalizeResolution (node:internal/modules/esm/resolve:327:11)
    at moduleResolve (node:internal/modules/esm/resolve:980:10)
    at defaultResolve (node:internal/modules/esm/resolve:1193:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:404:12)
    at ModuleLoader.resolve (node:internal/modules/esm/loader:373:25)
    at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:250:38)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:39)
    at link (node:internal/modules/esm/module_job:75:36) {
  url: '../server',
  code: 'ERR_MODULE_NOT_FOUND'
}

index.js

import "./server";

server.js

import express from "express";
const app = express();
const port = 3000;
app.get("/", (_req, res) => {
    res.status(200).json({ message: "Hello World" });
});
app.listen(port, () => {
    console.log(`App listening on http://localhost:${port}`);
});

What am I doing wrong that causes the ERR_MODULE_NOT_FOUND error? How can I fix this issue to correctly run my TypeScript project?

Update Angular 18 issue

I’m migrating an Ionic Angular Project to Angular 18.
After I updated the packages I got the following Errors:

Error:

1. If 'ion-searchbar' is an Angular component, then verify that it is part of this module.
2. If 'ion-searchbar' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

4         <ion-searchbar (ionInput)="searchData($event)" color="light" debounce="500"></ion-searchbar>

  src/app/modals/searchable-adress-modal-component/searchable-adress-modal-component.component.ts:7:18
    7     templateUrl: './searchable-adress-modal-component.component.html',
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SearchableAdressModalComponentComponent.


Error: src/app/modals/searchable-adress-modal-component/searchable-adress-modal-component.component.html:5:9 - error NG8001: 'ion-spinner' is not a known element:
1. If 'ion-spinner' is an Angular component, then verify that it is part of this module.
2. If 'ion-spinner' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

5         <ion-spinner *ngIf="loadDataSpinner" class="w-full justify-center mt-3 mb-3" color="primary"
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 name="lines-sharp"></ion-spinner>
  src/app/modals/searchable-adress-modal-component/searchable-adress-modal-component.component.ts:7:18
    7     templateUrl: './searchable-adress-modal-component.component.html',
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SearchableAdressModalComponentComponent.

Ionic Module is imported in App.Module.ts

@NgModule({
declarations: [AppComponent, ...],
imports: [        IonicModule.forRoot({
            scrollPadding: true,
            scrollAssist: true
        }),...],
providers: []
    providers: [
        {
            provide: RouteReuseStrategy,
            useClass: IonicRouteStrategy
        },
        {
            provide: ErrorHandler,
            // Attach the Sentry ErrorHandler
            useValue: SentryAngular.createErrorHandler()
        },
        {
            provide: SentryAngular.TraceService,
            deps: [Router]
        },
        {
            provide: APP_INITIALIZER,
            useFactory: () => () => {},
            deps: [TraceService],
            multi: true,
        },
    ],
    bootstrap: [AppComponent],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ]
}

So my modules are not importing correctly. I have Angular version 18.2.7 installed with ionic/angular v8.3.2
I’m struggling with that for hours. I tried to reinstall a couple of times, and took a look at the changeling but no hints for that.

How do I find out who or what is downloading an older version of my npm module? [closed]

Why is an old version of my npm module suddenly getting 274k downloads a week?

download stats

Its not to clear to me why an old version of my module is generating so many downloads. I have tried searching on github and looking at the dependents, but I see no popular modules or projects that are referencing "search-index": "1.0.6". I can’t seem to find any npm dependents that generate a lot of downloads either.

So where are these downloads coming from? What other options do I have to find out?

Why is an old version of my npm module suddenly getting 274k downloads a week?

download stats

Its not to clear to me why an old version of my module is generating so many downloads. I have tried searching on github and looking at the dependents, but I see no popular modules or projects that are referencing "search-index": "1.0.6". I can’t seem to find any npm dependents that generate a lot of downloads either.

So where are these downloads coming from? What other options do I have to find out?

Ethers.js: “contract runner does not support sending transactions” Error When Sending Ether in Contract Function

I’m encountering an error while trying to send Ether using Ethers.js in my decentralised Application. I have a Solidity function sendMoneyToCustomer that is marked as payable, but when I call it using Ethers.js, I get the following error:

Error: contract runner does not support sending transactions (operation=”sendTransaction”, code=UNSUPPORTED_OPERATION, version=6.13.3)

 // SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;

contract LoyaltyPoints {
    
    struct UserProfile {
        string username;
        string role;
    }

    mapping(address => UserProfile) private profiles;
    mapping(address => uint256) private balances;
    mapping(bytes32 => PurchaseRequest) private purchaseRequests;

    struct PurchaseRequest {
        address supermarket;
        uint256 amount;
    }

    modifier onlyRegisteredSupermarket() {
        UserProfile memory userProfile = profiles[msg.sender];
        require(bytes(userProfile.username).length > 0, "Supermarket does not exist");
        require(keccak256(bytes(userProfile.role)) == keccak256(bytes("supermarket")), "Not a Supermarket");
        _;
    }

    modifier onlyRegisteredCustomer() {
        UserProfile memory userProfile = profiles[msg.sender];
        require(bytes(userProfile.username).length > 0, "Customer does not exist");
        require(keccak256(bytes(userProfile.role)) == keccak256(bytes("customer")), "Not a Customer");
        _;
    }

    error InsufficientBalance(uint requested, uint available);

    function setProfile(string memory _username, string memory _role) public {
        profiles[msg.sender] = UserProfile(_username, _role);
    }

    function getProfile(address userAddress) public view returns (UserProfile memory) {
        return profiles[userAddress];
    }

    // Function to generate a QR code (purchase request) for a customer to scan and pay
    function generatePurchaseRequest(uint256 amount) public onlyRegisteredSupermarket returns (bytes32) {
        require(amount > 0, "Amount must be greater than zero");
        bytes32 qrCode = keccak256(abi.encodePacked(msg.sender, amount, block.timestamp));
        purchaseRequests[qrCode] = PurchaseRequest(msg.sender, amount);
        return qrCode;
    }

    // Function for customer to scan the QR code and pay
    function payWithQRCode(bytes32 qrCode) public payable onlyRegisteredCustomer {
        PurchaseRequest memory request = purchaseRequests[qrCode];
        require(request.supermarket != address(0), "Invalid QR code"); // Ensure valid request
        require(msg.value >= request.amount, "Insufficient amount sent");

        // Transfer ETH from customer to supermarket

        payable(request.supermarket).transfer(request.amount);
        
        
        // Remove the purchase request after payment is made
        delete purchaseRequests[qrCode];
    }

     function sendMoneyToCustomer(address payable customer) public payable onlyRegisteredSupermarket {
        require(customer != address(0), "Invalid customer address");
        balances[customer] += msg.value;
        customer.transfer(msg.value);
     }
}
                                                                                                                   
     import { defineStore } from "pinia";
import axios from "axios";
import { ethers } from 'ethers';
import { SHOPIFY_URL} from "~~/services/global.variables";





export const useShopBrandsStore = defineStore('shopBrands', {
    state: () => ({
        name: "",
        full_name: "",
        my_profile : null,
        contractAddress: "0x5FbDB2315678afecb367f032d93F642f64180aa3",
        abi : [
            {
              "inputs": [
                {
                  "internalType": "uint256",
                  "name": "requested",
                  "type": "uint256"
                },
                {
                  "internalType": "uint256",
                  "name": "available",
                  "type": "uint256"
                }
              ],
              "name": "InsufficientBalance",
              "type": "error"
            },
            {
              "inputs": [
                {
                  "internalType": "uint256",
                  "name": "amount",
                  "type": "uint256"
                }
              ],
              "name": "generatePurchaseRequest",
              "outputs": [
                {
                  "internalType": "bytes32",
                  "name": "",
                  "type": "bytes32"
                }
              ],
              "stateMutability": "nonpayable",
              "type": "function"
            },
            {
              "inputs": [
                {
                  "internalType": "address",
                  "name": "userAddress",
                  "type": "address"
                }
              ],
              "name": "getProfile",
              "outputs": [
                {
                  "components": [
                    {
                      "internalType": "string",
                      "name": "username",
                      "type": "string"
                    },
                    {
                      "internalType": "string",
                      "name": "role",
                      "type": "string"
                    }
                  ],
                  "internalType": "struct LoyaltyPoints.UserProfile",
                  "name": "",
                  "type": "tuple"
                }
              ],
              "stateMutability": "view",
              "type": "function"
            },
            {
              "inputs": [
                {
                  "internalType": "bytes32",
                  "name": "qrCode",
                  "type": "bytes32"
                }
              ],
              "name": "payWithQRCode",
              "outputs": [],
              "stateMutability": "payable",
              "type": "function"
            },
            {
              "inputs": [
                {
                  "internalType": "address payable",
                  "name": "customer",
                  "type": "address"
                }
              ],
              "name": "sendMoneyToCustomer",
              "outputs": [],
              "stateMutability": "payable",
              "type": "function"
            },
            {
              "inputs": [
                {
                  "internalType": "string",
                  "name": "_username",
                  "type": "string"
                },
                {
                  "internalType": "string",
                  "name": "_role",
                  "type": "string"
                }
              ],
              "name": "setProfile",
              "outputs": [],
              "stateMutability": "nonpayable",
              "type": "function"
            }
          ],
        
           
    }),
    actions: {
        async connectWallet ()  {
            console.log("Ethers:", ethers);
        
                
           const provider = new ethers.BrowserProvider(window.ethereum)
                console.log("Ethers:", ethers);
                console.log("Provider:", provider);
                await provider.send("eth_requestAccounts", []);
                const signer = await provider.getSigner();
                console.log('s',signer)

                const walletAddress = await signer;

                // Save wallet address and provider in localStorage
               
                localStorage.setItem("signer", JSON.stringify(signer));
                return provider.getSigner();
            
        },
        async setProfile(signer, username, role)  {
            const contract = new ethers.Contract(this.contractAddress, this.abi, signer);
            const tx = await contract.setProfile(username, role);
            await tx.wait();
        },
        async getProfile (signer)  {
            const contract = new ethers.Contract(this.contractAddress, this.abi, signer);
            console.log('signer',signer)
            const userAddress = await signer; // Get the user's wallet address
            const profile = await contract.getProfile(userAddress);
            this.my_profile = profile
            return profile;
        },
        
        
        async generatePurchaseRequest  (signer, amount)  {
            const contract = new ethers.Contract(contractAddress, abi, signer);
            const qrCode = await contract.generatePurchaseRequest(amount);
            return qrCode;
        },
        
        async payWithQRCode  (signer, qrCode, amount)  {
            const contract = new ethers.Contract(contractAddress, abi, signer);
            const tx = await contract.payWithQRCode(qrCode, { value: ethers.utils.parseEther(amount) });
            await tx.wait(); 
        },
        
        async sendMoneyToCustomer  (signer, customerAddress, amount)  {
            const contract = new ethers.Contract(this.contractAddress, this.abi, signer);
            console.log('aaa',amount)
            const ethValue = ethers.parseEther(amount)
            console.log('eth',ethValue)
            const tx = await contract.sendMoneyToCustomer(customerAddress, {value: ethValue},  // Convert the amount from ETH to Wei
            );
            await tx.wait();  // Wait for the transaction to be mined
        },
        
    
       
      
       
        
      
        
     
   

 

  

     
      
        
      
   
       
    
    
       
        
      
      
    }
});   
    
Here's what I've checked so far:
The signer is correct, and I can call other non-payable functions like setProfile with the same signer.and its qorking when call setProfile

Fast API POST Request to retrieve data from Google Cloud MySQL giving Recurring 404 Error

I am creating a web app that makes use of the amazon product advertising API. I haven’t started on this part of the functionality as I am still creating the base web app. I have already created a desktop app version in python with CTkinter so I’m using this as a design aid to help me. For the web app I have decided to use Fast-API to connect the frontend to my python backend and my MySQL database instance hosted on the google cloud. I have managed to create the first few endpoints that handle user logins. Now I am starting to create the endpoints that control the user data stored in the SQL DB; I wanted to start with a simple request at first to ease myself into the more complicated stuff so I am currently trying to set up a theme switcher (to switch the web app theme from dark mode to light mode).

I started to set it up the same as my other POST requests, with CORS middleware setup, ensuring the request has the same name in the frontend as the backend and is pointing to the correct request URL. However, it continually gives me error 404 when testing. I have tried all sorts including setting up the CORS Middleware the same as the other requests that all work; Setting up the app.options for this specific request; trying different sql statements, using logging to show where it fails, clearing by browser cache/using incognito window etc etc. After 2 days of trying this I have given up with this and wish for someone to read my frontend, backend and middelware setup for this specific request to see if I’m missing something extremely obvious.

Please find my project code below:

# Python / Fast-API

# Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Your frontend origin
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Pydantic model to handle the incoming data
class ThemeUpdateRequest(BaseModel):
    username: str

# Options for Update-Theme
@app.options("/update-theme/")
async def options_update_theme():
    return {
        "allow": "POST, OPTIONS",
        "access-control-allow-origin": "http://localhost:5500",
        "access-control-allow-methods": "POST, OPTIONS",
        "access-control-allow-headers": "Content-Type, Authorization"
    }

# POST Request /update-theme/
@app.post("/update-theme/")
def update_theme(data: ThemeUpdateRequest, connection=Depends(get_connection)):
    try:
        print(f"Received request to /update-theme/ for user:{data.username}")
        with connection.cursor() as cursor:
            # Fetch the current theme value for the user
            cursor.execute("SELECT light_dark FROM user_frame WHERE username = %s", (data.username,))
            theme_value = cursor.fetchone()

            if theme_value is None:
                print(f"/update-theme/ failed due to no user frame found for user: {data.username}")
                insert_frame(connection, data.username)
                cursor.execute("SELECT light_dark FROM user_frame WHERE username = %s", (data.username,))
                theme_value = cursor.fetchone()

            # Toggle the theme value
            new_theme_value = 1 if theme_value[0] == 0 else 0

            # Update the theme in the database
            cursor.execute("UPDATE user_frame SET light_dark = %s WHERE username = %s", (new_theme_value, data.username))
            connection.commit()
            print(f" Theme has been updated to {new_theme_value} for user:{data.username}")

            return {"status": "Theme updated successfully", "new_theme_value": new_theme_value}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to Update Theme: {str(e)}")
# JavaScript

const toggleThemeButton = document.getElementById("toggle-theme")

toggleThemeButton.addEventListener("click", async function () {
  const username = localStorage.getItem("username")
  if (!username) {
    errorMessage.textContent = "Username not found. Please log in first."
    return
  }

  try {
    console.log("Sending request to update theme")
    const response = await fetch("http://localhost:8000/update-theme/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username }),
    })

    console.log("Response received:", response)

    if (response.ok) {
      const result = await response.json()
      document.body.classList.toggle("dark-mode", Number(result.new_theme_value) === 1)
      errorMessage.textContent = ""
    } else {
      const errorData = await response.json()
      console.error("Error data:", errorData)
      errorMessage.textContent = errorData.detail || "Failed to update theme."
    }
  } catch (error) {
    console.error("Fetch error:", error)
    errorMessage.textContent = "An error occurred while updating the theme."
  }
})

Furthermore, once I have got this theme switching button working I am going to add functionality to my login function that will automatically change the theme to the last theme the user was using, essentially keeping their preferences saved.