Electron Preload file Disables ‘Require’ functionality with nodeIntegration set to false, is that correct?

I’m programming my first Electron application and trying to follow best security practices. I have a preload script that is attempting to load a local file required for a renderer page. I set nodeIntegration to false and contextIsolation to true. I thought those settings only disabled node.js functionality for the renderer pages and to use node functionality you were suppose to make an ipc call to send and request data via contextBridge from the preload. However with nodeIntegration disabled, I cannot seem to require anything other than ‘electron’. I cannot even require(‘path’) or require(‘fs’) in the preload which is where i thought we were suppose to have that type of functionality. Is that functioning as you would expect and I’m misunderstanding something? Is it safe to leave nodeIntegration True so i can have this functionality?

This works with nodeIntegration : false

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
    loadIndexPage: () => ipcRenderer.send('load-index-page')
});

No other modules work(with nodeInt: false) however including

const { contextBridge, ipcRenderer } = require('electron');
const path = require('path');
const fs = require('fs');

contextBridge.exposeInMainWorld('electronAPI', {
    loadIndexPage: () => ipcRenderer.send('load-index-page')
});

From here my preload fails because it cannot find module path or fs which is weird. Anywho thanks for any help you can give.

Syntax error but I don’t understand where it’s wrong

I’ve been trying to write a plugin for betterdiscord in JS and everytime I run it it gives me a weird error


module.exports = () => ({
             ^

SyntaxError: Unexpected token '.'
at Object.compileFuncion (node:vm:360:18)
at Function.U

Can anyone help me? Here’s the code itself


module.exports = class SpotifyFix {
 start() {
    // Saves the original function
    XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;

    // Create new function to filter out URLs
    var myOpen = function(method, url, async, password) {
        //redirects the /pause to /play (cancels it because spotify is already playing)
        if (url == "https://api.spotify.com/v1/me/player/pause") {
            url == "https://api.spotify.com/v1/me/player/play"
        
        this.realOpen(method, url, async, password);
    

    // Overwrite original open with modded version
    XMLHttpRequest.prototype.open = myOpen;
        
       }
    }
}

    
stop() {
        XMLHttpRequest.prototype.open = XMLHttpRequest.prototype.open;
            }
        }

I already tried asking around and people told me that the export syntax is wrong but the documentation write it that way.

Can I get the Fullcalendar default eventContent from Fullcalendar Vue component

Currently using the Fullcalendar Vue component and everything is working ok. However, I added tooltips to the events using DaisyUI and that raised a problem.

Adding the DaisyUI tooltip to an event involves putting the Fullcalendar event within a div like this:

<div class="tooltip" :data-tip="formatTooltip(event)">
    *** event content **
</div>

To do this I used content injection, so I then lost the default event content as formatted by fullcalendar and had to specify the event content. Here’s what I have now:

<FullCalendar ref='fullCalendar' :options="calendarOptions">
   <template #eventContent="{ event }">
      <div class="tooltip" :data-tip="formatTooltip(event)">
         <div class="text-sm font-medium ">{{ formatDate(event.start) +  ' - ' +  formatDate(event.end) }}</div>
         <div>{{ event.title }}</div>
      </div>
   </template>
</FullCalendar>

This works ok for the timeGridWeek and TimeGridDay views, but now the dayGridMonth view doesn’t look right.

Perhaps, if I could inject the default eventContent as formatted by Fullcalendar, then maybe Fullcalendar would reformat the content properly for the dayGridMonth.

Is there a variable which holds the event formatted by fullcalendar in the fullcalendar vue component? If so, then this might work:

<FullCalendar ref='fullCalendar' :options="calendarOptions">
   <template #eventContent="{ event }">
      <div class="tooltip" :data-tip="formatTooltip(event)">
         {{ defaultFormattedEventContent }}
      </div>
   </template>
</FullCalendar>

Where could I pick up the defaultFormattedEventContent from the fullcalendar vue component?

Alternatively, as a work-around, I could try using v-if to inject different content format for the dayGridMonth. How do I get the currently active view from the fullcalendar vue component?

Thanks for any help you can provide.

Error in node.js.. Cannot set header after they are sent to clients [duplicate]

So i am building a blog and I am trying to render different paths using the router parameter but it keeps bring up this error every time I try to print another route. Cant really explain more but i will place my code here.

import express from "express";
import bodyParser from "body-parser";
import lodash from "lodash";

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

app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));

let globalarray = [];

app.get("/", (req, res) => {
  res.render("index.ejs", {
    arr: globalarray,
  });
});

app.get("/contact", (req, res) => {
  res.render("contact.ejs");
});

app.get("/create", (req, res) => {
  res.render("create.ejs");
});

app.post("/submit", (req, res) => {
  const posts = {
    category: req.body["category"],
    title: req.body["title"],
    post: req.body["post"],
  };

  globalarray.push(posts);
  res.redirect("/");
});

app.get("/globalarray/:pathName", (req, res) => {
  let requestedName = _.lowerCase(req.params.pathName);

  globalarray.forEach((item) => {
    if (requestedName === _.lowerCase(item.category)) {
      res.render("post.ejs");
    }
  });
});

This last part is where the problem is. Please I need an assist with this.

I have tried returning, but nothing is working.

golang/wasm error (Uncaught (in promise) TypeError: import object field ‘gojs’ is not an Object)

Ive been using Golang and WASM to make a basic app (a basic game, but its not really that important to this question as you will soon find out) and learn about the technologies, so I set up a project and it was working fine… until it just kind of stopped working right? I’m not quite sure what I did but the code stopped executing with no errors other than
"Uncaught (in promise) TypeError: import object field 'gojs' is not an Object".
From this I know that it has to do with fetch() and I have confirmed this by commenting out different parts of my code until I narrowed it down to this line:

//errors here
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
    //not here (obviously not running though)
    go.run(result.instance);
});

this also isn’t my original app, as I created a new one and (this time made sure to) copy and paste every line of code directly from this article: https://golangbot.com/webassembly-using-go/ so that I would know for sure that its not a problem with my code. (as I wouldn’t have written it)

Everything I tried to do to fix this (in order):

  • comment out code I wrote recently (websocket stuff)
  • comment out all my go code
  • comment out run
  • reinstall golang and get a new wasm_exec
  • comment out WebAssembly.instantiateStreaming (error stoped showing here)
  • created a new project and made sure to only copy and paste from this tutorial: https://golangbot.com/webassembly-using-go/
  • reinstall golang and get a new wasm_exec (again)

here’s my code:

assets/main.go

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Go Web Assembly")
}

server/server.go

package main

import (
    "fmt"
    "net/http"
)

func main() {
    err := http.ListenAndServe(":9000", http.FileServer(http.Dir("./static")))

    if err != nil {
        fmt.Println("Failed to start server", err)
        return
    }
}

static/index.html

<html>
    <head>
    <meta charset="utf-8"/>
    <script src="wasm_exec.js"></script>
    <script>
        const go = new Go();
        WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
        go.run(result.instance);
            });
        </script>
    </head>
<body></body>
</html>

static/wasm_exec.js

I'm not putting this here unless I need to...

the commands I used (from project root):
go run server/server.go (to run the server)
GOOS=js GOARCH=wasm go assets/build main.go (to build the wasm file, I know I don’t have to drag and drop the files into the static folder this is just temp)

This is my first question on StackOverflow so if you need anything I didn’t post here just let me know.
Ive already tried my best to find something on the internet but I couldn’t find anything on this error please help.

TypeError: Cannot assign to read only property ‘performance’ of object ‘[object global]’

Error:

This error was only popping up for me when running CI for jest. I could not catch it locally in any way. Error text:

FAIL src/utils/message.test.ts
  ● Test suite failed to run

    TypeError: Cannot assign to read only property 'performance' of object '[object global]'

       5 |
       6 | jest
    >  7 |   .useFakeTimers({ legacyFakeTimers: false })
         |    ^
       8 |   .setSystemTime(new Date(fakeTime));
       9 |
      10 | jest.mock('src/constants/env', () => {

      at hijackMethod (../node_modules/@sinonjs/fake-timers/src/fake-timers-src.js:946:32)
      at Object.install (../node_modules/@sinonjs/fake-timers/src/fake-timers-src.js:1733:17)
      at Object.<anonymous> (src/utils/message.test.ts:7:4)

Is there like a clickcounter function that records the amount of clicks you do on an element in Javascript?

Currently I have a table and a javascript function that makes it so that when I click an table cell all the other table cells in the row disappear and the clickedcell gets moved to the leftmost of the table row, there will be info sliding out from the right and etc. However I want to make it so that when you click it a second time everything returns back to their normal state.

I’m just wondering if javascript can track how many times the user click on an element, I’m thinking of doing something like at odd number of clicks on an element the codes will hide the other table cells and move it while at even number of clicks it returns everything back to normal.

html

<table id='TrendGames'>
    <tbody>
        <tr>
                <td id="cell1"> Cell 1
                <img class='GameCover' src='.png' alt="cell1" />
                </td>
                <td id="cell2">Cell 2
                <img class='GameCover' src='.png' alt="cell2" />
                </td>
                <td id="cell31">Cell 3
                <img class='GameCover' src='.png' alt="cell3" />
                </td>
                <td id="cell4">Cell 4
                <img class='GameCover' src='.png' alt="cell4" />
                </td>
        </tr>
       </tbody>
</table>

javascript

document.addEventListener('DOMContentLoaded', function() {
  var table = document.getElementById('TrendGames');
  table.addEventListener('click', function(event) {
    var clickedCell = event.target.closest('td');
    if (clickedCell) {
      handleCellClick(clickedCell);
    }
  });
});

function handleCellClick(clickedCell) {
  var row = clickedCell.parentElement;
  var cells = row.children;

  // Hide other cells and rearrange the clicked cell
  for (var i = 0; i < cells.length; i++) {
    if (cells[i] !== clickedCell) {
      cells[i].style.display = 'none';
    }
  }
  row.insertBefore(clickedCell, row.firstChild); // Move to the leftmost
  clickedCell.colSpan = cells.length
  // Open the slider and display information
  openSlider(clickedCell);
}

function openSlider(cell) {
  // Implement the slider logic here
  console.log(cell.id)
}

If there’s a better way of doing this pls let me know.

Discord bot can’t see user’s message-content

I have created a Discord Bot using replit and node.js, and upon testing the bot, I realized that it couldn’t see the content of a sent message in the Discord Server. My bot has admin status, and I’ve enabled all 3 settings for Privileged Gateway Intents in the Discord Developer Portal, but my JSON of the received message (from block 6) still comes out as “content: “”,” (i.e content empty). I’ve also tried to reboot the bot, and tried disable and enable the settings in the Privileged Gateway Intents but still nothing. The bot sees the message, just not its content.

Here is my code:

const express = require("express");
const app = express();
app.listen(3000, () => {
  console.log("Project is running!!");
});
app.get("/", (req, res) => {
  res.send("Hello World!");
});
const { Client } = require("discord.js");
const client = new Client({
  intents: [32767], // This number represents all available intents
});
client.on("ready", () => {
  console.log('Bot has logged in as ${client.user.tag}');
});
client.on("messageCreate", (message) => {
  console.log('Received message: ${JSON.stringify(message)}');
  if (message.content === "ping") {
    message.reply("pong");
  }
});
client.login(process.env.token);

In this case, the log prints the following:

Project is running!!
Bot has logged in as ${client.user.tag}

And if a message is sent in the server the log prints:

Received message:
{"channelId":"xxxxxxxxxxxxxx","guildId":"xxxxxxxxxxxx","id":"xxxxxxxxxxxxx","createdTimestamp":xxxxxxxxxxxxx,"type":0,"system":false,"content":"","authorId":"xxxxxxxxxxxx","pinned":false,"tts":false,"nonce":"xxxxxxxxxxxxx","embeds":[],"components":[],"attachments":[],"stickers":[],"position":null,"roleSubscriptionData":null,"resolved":null,"editedTimestamp":null,"mentions":{"everyone":false,"users":[],"roles":[],"crosspostedChannels":[],"repliedUser":null,"members":[],"channels":[]},"webhookId":null,"groupActivityApplicationId":null,"applicationId":null,"activity":null,"flags":0,"reference":null,"interaction":null,"cleanContent":""}

where the content at subject 7 is empty no matter the actual content of the sent message.

I suspect it might have to do with block 4, more precisely

intents [32767]

This line is AI generated, and said to go hand in hand with the newest patch of discord.js, but I’m not too sure since its not working. Can’t find something else online tho so I am testing my luck here.

I’ve also tried changign block 4 in my previous Javascript-code for:

const { Client, Intents } = require("discord.js");
const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
});

But this gives me the error message:

/home/runner/Leaguelegendernas-Maid/index.js:14
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
                    

TypeError: Cannot read properties of undefined (reading 'FLAGS')
    at Object.<anonymous> (/home/runner/Leaguelegendernas-Maid/index.js:14:21)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49

It goes without saying, but I can’t ever trigger the “pong” response. Unless i remove the “ping” in the code for an empty string, then it works.

Anyone have a fix for this? Most of thanks!

creating a script to automate tik tok [closed]

reetings to everyone who came here! I need a script to automatically like comments on TikTok under a video. One of the key goals of the script should be to create the impression of natural activity. I mean that likes should not appear instantly, like out of a bucket. Instead, it is expected that likes will come gradually, for example, over the course of a day – about 1000 likes.

As for the programming language, I’m ready to consider any option. I don’t have a big budget, but I’m willing to discuss any reasonable amount if necessary. The main condition is to avoid the possibility of a shadow ban.

If you have any questions, don’t hesitate to ask. I’m ready to answer them. Thank you for attention!

I tried to find developers on freelance sites, so far without success

problems with simple library in javascript Error: “implicitly has an ‘any’ type.”

I’m trying to create a library in javascript that makes some requests to an API, I want to create a module that I can publish in npm and that can be used from any framework like angular or react
I have the following code of my class with these files to publish it

masivPushWebService.js

import { MANAGMENT_API_URL, WEB_PLATFORM } from './constants.js';
import { sendPost } from './httpUtils.js';

class masivPushWebService {

    constructor(externalApplicationId) {
        this.externalApplicationId = externalApplicationId;
    }

    async registerToken(payload) {
        let body = {
            token: payload,
            platform: WEB_PLATFORM,
            externalApplicationId: this.externalApplicationId
        }
        const response = await sendPost(MANAGMENT_API_URL + "tokens", body)
        return response
    }

}

export default masivPushWebService;

package.json

{
  "name": "npm-servtest",
  "version": "1.0.0",
  "description": "",
  "main": "src/masivPushWebService.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

When I publish it, it publishes without problems, however when I install it, for example in an Angular project, it gives me the following error

Could not find a declaration file for module ‘npm-servtest’. ‘…/masivPushWebService.js’ implicitly has an ‘any’ type.
Try npm i --save-dev @types/npm-servtest if it exists or add a new declaration (.d.ts) file containing `declare module ‘npm-servtest’;

I am not an expert in front and I have tried to find the solution but I can’t find it, could you help me?

I tried to place the tsconfig.json file but it did not solve the problem

SignalR and SqlTableDependency trigger problem: no data after post

In my ASP.NET Core project, when I add data with Ajax, I list data in success.
Also, after updating on the Detail page, I redirect to the Index page and see the data I updated here.
The codes were working properly and error-free.
Then I added SignalR and SqlTableDependency libraries to my project. I cannot do listing operations because the trigger named Sender occurs in the relevant table in the database. While I can list with Ajax, now I have to refresh the page or when I update on a page and go to Index, I have to refresh the Index page to see the updated data.
There are still no errors, everything works correctly, but I have to refresh the page constantly.

My code that worked properly before I added SignalR and SqlTableDependency,

AccountingController.cs

[HttpGet]
public async Task<IActionResult> GetExpenseByUser()
{
    var user = await _userManager.FindByNameAsync(User.Identity.Name);
    int id = user.Id;
    var client = _httpClientFactory.CreateClient();
    var responseMessage = await client.GetAsync($"https://localhost:7198/api/Expense/ListExpenseByUser?id={id}");
    if (responseMessage.IsSuccessStatusCode)
    {
        var jsonData = await responseMessage.Content.ReadAsStringAsync();
        var values = JsonConvert.DeserializeObject<List<ResultExpenseByUserDto>>(jsonData);
        return Json(values);
    }
    return View();
}

Index.cshtml,

<script>
    $(document).ready(function () {
        function listExpense() {
            $.ajax({
                type: "Get",
                url: "/Accounting/GetExpenseByUser",
                success: function (value) {
                    $("#tableExpense tbody").empty();
                    var tablerow;
                    $.each(value, (index, item) => {
                        tablerow = $("<tr/>");
                        tablerow.append(`<td><a class="fw-semibold text-primary">#${item.periodID}</a></td>`)
                        tablerow.append(`<td>${item.createUser}</td>`)
                        tablerow.append(`<td>${item.periodMonth}</td>`)
                        tablerow.append(`<td>${item.periodYear}</td>`)
                        switch (item.paymentStatus) {
                            case 9999:
                                tablerow.append(`<td><span class="badge bg-warning-transparent">Bekleniyor</span></td>`)
                                break;
                            case 9998:
                                tablerow.append(`<td><span class="badge bg-warning-transparent">Onay Sürecinde - Yönetici</span></td>`)
                                break;
                            case 1:
                                tablerow.append(`<td><span class="badge bg-warning-transparent">Ödeme Bekleniyor - Muhasebe</span></td>`)
                                break;
                            case 2:
                                tablerow.append(`<td><span class="badge bg-success-transparent">Ödeme Yapıldı</span></td>`)
                                break;
                            case 3:
                                tablerow.append(`<td><span class="badge bg-dark-transparent">Gecikmiş Ödeme</span></td>`)
                                break;
                            case 4:
                                tablerow.append(`<td><span class="badge bg-danger-transparent">İptal Edilen Ödeme</span></td>`)
                                break;
                        }
                        let formattedTotalAmount = parseFloat(item.totalAmount).toLocaleString('tr-TR', { minimumFractionDigits: 2 });
                        tablerow.append(`<td>₺${formattedTotalAmount}</td>`);
                        tablerow.append(`<td><a href="#" class="btn btn-primary-light btn-icon btn-sm"><i class="ri-eye-line"></i></a> <a href="/Accounting/ExpenseTransactions/${item.expenseID}" class="btn btn-primary-light btn-icon btn-sm"><i class="ri-send-plane-2-line"></i></a></td>`);
                        $("#tableExpense").append(tablerow);
                    });
                },
                error: function (xhr, status, error) {
                }
            });
        }

        $("#btnAddExpense").click(function () {
            $.ajax({
                type: "Post",
                url: "/Accounting/Index",
                success: function () {
                    listExpense();

                    Toastify({
                        text: 'Harcama Dönemi Oluşturuldu',
                        duration: 3000,
                        gravity: "top",
                        position: 'right',
                        backgroundColor: "#4CAF50",
                        stopOnFocus: true,
                    }).showToast();
                },
                error: function (xhr, status, error) {
                    var errorMessage = xhr.responseJSON ? xhr.responseJSON : "Bu Döneme Ait Kayıt Bulunmaktadır";
                    Toastify({
                        text: errorMessage,
                        duration: 3000,
                        gravity: "top",
                        position: 'right',
                        backgroundColor: "#f64e60",
                        stopOnFocus: true,
                    }).showToast();
                }
            });
        });
    });
</script>

Has anyone encountered this situation before? How do we solve this situation.

How to use logical operators with 3 variables in Apps Script to generate 1 of 3 different templates

I want to create Google docs from a Google sheet – loosely following this

The program should read the value in row 1 and determine which of the 3 Google Doc templates to use

I have 3 three different expressions, but I’m not getting past the first phrase.

//should use template for 'a'
if ((row[14] != 'b') && (row[14] != 'c')) return; 
//should use template for 'b'
if ((row[14] != 'a') && (row[14] != 'c')) return; 
//should use template for 'c'
if ((row[14] != 'a') && (row[14] != 'b')) return; 

…again I don’t know what I’m doing so I’m sure there’s a much simpler way to do it 🙂

Angular Material SnackBar showing without styles

I am trying to implement a Angular Material SnackBar and it is rendering, but without proper styles.

My code:

notification-snack-bar.component.html

<div class="notification-snack-bar-container flex">
  <div>
    <span class="mat-warn-color"
      >An Error Occurred: {{ message }}<br /><span *ngIf="timerCount > 0"
        >Timer: {{ timerCount }}</span
      ></span
    ><br /><span>See the console for the full error.</span>
  </div>
  <button mat-button color="accent" (click)="dismiss()">{{ action }}</button>
</div>

notification-snack-bar.component.ts

import { Component, Inject } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBar } from '@angular/material/snack-bar';
import { NotificationService } from './notification.service';

@Component({
  selector: 'app-notification-snack-bar',
  templateUrl: 'notification-snack-bar.component.html',
  styles: [
    `
      .flex {
        justify-content: space-between;
        align-items: center;
      }
      .notification-snack-bar-container > div {
        overflow: hidden;
      }
      span {
        width: 100%;
        display: inline-block;
      }
      span > span {
        padding: 0;
      }
      button {
        padding: 0;
      }
    `,
  ],
})
export class NotificationSnackBarComponent {
  // set the default values
  public action = 'dismiss';
  public interval: any = null;
  public message = 'Unknown error...';

  // track the time for the timer
  public timerCount = 0;

  constructor(
    @Inject(MAT_SNACK_BAR_DATA) public data: any,
    public snackBar: MatSnackBar,
    private notificationService: NotificationService,
  ) {
    // load the properties from the data passed in
    // if the data.message is a string -> pass it through
    // else if the data.message is an object and it has the .message property -> pass it through
    // else indicate an unknown error
    console.log(data)
    this.message =
      typeof data.message === 'string'
        ? data.message
        : typeof data.message === 'object' && data.message.message
          ? data.message.message
          : 'Unknown Error...';
    this.action = data.action ? data.action : 'dismiss';
  }

  /**
   * start a timer for the given amount of seconds
   * @param timerDuration: number
   */
  startTimer(timerDuration: number) {
    this.timerCount = timerDuration;
    this.interval = setInterval(() => {
      if (this.timerCount > 0) {
        this.timerCount--;
      } else {
        this.timerCount = 60;
      }
    }, 1000);
  }

  // close the snack bar
  dismiss(): void {
    // indicate on the service that the error is being closed
    this.notificationService.errorBeingDisplayed = false;
    // dismiss the actual snack bar
    this.snackBar._openedSnackBarRef!.dismiss();
  }
}

header.component.ts (where the SnackBar component is called)

import { Component, OnInit, NgZone } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { NotificationService } from '../notification/notification.service';
import { NotificationSnackBarComponent } from '../notification/notification-snack-bar.component';


@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
  constructor(
    private snackBar: MatSnackBar,
    private notificationService: NotificationService,
    private zone: NgZone,


  ) { }

  ngOnInit() {
    this.notificationService.displayError$.subscribe((error) => {
      // Load the given component into the snack-bar.
      this.zone.run(() => {
        this.snackBar.openFromComponent(NotificationSnackBarComponent, {
          data: {
            message: error,
          },
        });
      });
    });
  }
}

And this is what renders:
enter image description here
enter image description here

Any help would be much appreciated!

How to pass the get parameter in a post request? [closed]

card_number: pay_form.querySelector('[name="card"]').value,
yy: parseInt(pay_form.querySelector('[name="date"]').value.split(' / ')[1]),
mm: parseInt(pay_form.querySelector('[name="date"]').value.split(' / ')[0]),
cvv: pay_form.querySelector('[name="cvc"]').value,
sum: ,

There is such a code, you need to insert the value of the get parameter test.com?sum=100 into “sum”

Unable to read any config from Karate-config.js

I have created the karate-config.js under src/test/java
Tried directly using baseUrl or providing the systems property didn’t worked

function fn() {

  var config = {
      env: env,
      baseUrl: 'http://testDev1/service',
      headers: headers,
   };

   var env = karate.env ? karate.env : "dev";
      var baseUrl = 'https://' + env + '.service/endpt';
      var version = '0.1.0';
    karate.log("The value of env is: ",  env);
  var headers = {
    'accept': 'application/json',
    'Content-type': 'application/json',
    'SRV.DEVICEID': 'test1.com',
    'CONSUMER.ID': '2caf5274'
  };
 var qaheaders = {
    'accept': 'application/json',
    'Content-type': 'application/json',
    'SRV.DEVICEID': 'test22.com',
    'CONSUMER.ID': '1111'
  };

  switch (env) {
    case "stg1":
      config.baseUrl = "https://testStg1/service";
      env = "stg";
      break;
    case "qa":
      config.baseUrl = "https://testqa1/service";
      env = "qa";
      headers = qaheaders;
      break;
   case "stg2":
      config.baseUrl = "https://teststg2/service";
      env = "qa";
      headers = headers;
      break;

  }

  return config;
}

in feature file I am doing something like this


@test122
Feature: Basic end-to-end testing

  Background:
    * url baseUrl

  Scenario:
    Given print baseUrl
    Given print env

Test runner file

class BasicApiTestingRunner {

    @Karate.Test
    Karate testBasicApi() {
        System.setProperty("-Dkarate.config.dir", "/Users/user/Development/project/src/test/java/karate-config.js");
        return Karate.run()
                .tags("@test122")
                .relativeTo(getClass());
    }
}

Error :

* url baseUrl
js failed:
>>>>
01: baseUrl
<<<<
org.graalvm.polyglot.PolyglotException: ReferenceError: "baseUrl" is not defined
- <js>.:program(Unnamed:1)

PS. similar code is working under 0.9.6 version current upgraded version 1.4.0

as per official document https://github.com/karatelabs/karate?tab=readme-ov-file#karate-configjs, I tried same file structure as well still same behavior.