Error 500 with RTK Query creatApi in React app

I created this api usrion RTK Query

`import { createApi, fetchBaseQuery } from “@reduxjs/toolkit/query/react”;

export const usersApi = createApi({
reducerPath: “users”,
tagTypes: [“Users”],
baseQuery: fetchBaseQuery({
baseUrl: “/api/users”,
prepareHeaders: (headers) => {
const accessToken = sessionStorage.getItem(“nh_accessToken”);
if (accessToken) {
headers.set(“authorization”, Bearer ${accessToken});
headers.set(“Content-Type”, “application/json”);
}

  return headers;
},

}),
endpoints: (builder) => ({

getUsers: builder.query({
  query: () => "/mg",
}),

registerUser: builder.mutation({
  query: (body) => ({
    url: "/register",
    method: "POST",
    body
  }),
  invalidatesTags: ["Users"]
}),

}),
});

export const { useGetUsersQuery, useRegisterUserMutation } = usersApi;
`

The getUsers endpoint works just fine, but the registerUser endpoint is always returning an error 500

This is the component where I call the endpoint

import { Link as RouterLink } from "react-router-dom";

import { Button, Form, Input, Typography } from "antd";
import { LockOutlined, MailOutlined, UserOutlined, PhoneOutlined, HomeOutlined } from "@ant-design/icons";
import { getStyles } from "../utils/getStyles";
import { AuthLayout } from "../layouts/AuthLayout";
import { useForm } from "../../hooks";
import { useRegisterUserMutation } from "../../app/apis/users/usersApi";

const { Text, Link } = Typography;

export const RegisterPage = () => {

  const [registerUser, response] = useRegisterUserMutation();

  const { email, password, firstName, lastName, phone, residentialUnit, propertyId, onInputChange } = useForm({
    firstName: "",
    lastName: "",
    phone: "",
    email: "",
    residentialUnit: "",
    propertyId: "",
    password: "",
  });

  const onSubmit = async (e) => {
  e.preventDefault();

  const firstWordFromName = firstName.split(" ")[0];
  const firstWordFromLastName = lastName.split(" ")[0];
  
  const userData = {
    firebaseUser: {
      displayName: firstWordFromName + " " + firstWordFromLastName,
      email: email,
      phoneNumber: phone,
      password: password,
    },
    mongoUser: {
      firstName: firstName,
      lastName: lastName,
      email: email,
      phone: phone,
      residentialUnit: residentialUnit,
      propertyId: propertyId,
    },
  };

  console.log('userData',userData)

  await registerUser(userData)
      .unwrap()
      .then(() => {
        console.log('No hay error')
      })
      .then((error) => {
        console.error(error)
      })
}

  const styles = getStyles();

  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  return (
    <>
      <AuthLayout
        title="New User"
      >
        <Form
          onSubmitCapture={onSubmit}
          onChange={onInputChange}
          onFinish={onFinish}
          layout="vertical"
          requiredMark="optional"
          className="animate__animated animate__fadeIn"
        >
          <Form.Item
            name="firstName"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input prefix={<UserOutlined />} value={firstName}/>
          </Form.Item>
          <Form.Item
            name="lastName"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input prefix={<UserOutlined />} value={lastName} />
          </Form.Item>
          <Form.Item
            name="phone"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input prefix={<PhoneOutlined />} value={phone} />
          </Form.Item>
          <Form.Item
            name="email"
            rules={[
              {
                type: "email",
                required: true,
              },
            ]}
          >
            <Input prefix={<MailOutlined />} value={email}/>
          </Form.Item>
          <Form.Item
            name="residentialUnit"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input prefix={<HomeOutlined />} value={residentialUnit}/>
          </Form.Item>
          <Form.Item
            name="propertyId"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input prefix={<HomeOutlined />} value={propertyId}/>
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              type="password"
              placeholder="Password"
              value={password}
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: "0px" }}>
            <Button block type="primary" htmlType="submit">
              Register
            </Button>
          </Form.Item>
        </Form>
      </AuthLayout>
    </>
  );
};

This is what I see in console
console log

And the request payload is not empty
payload

I try this locally with postman ant it works perfectly, but for some reason from react is not working.

I don’t know what else to look here, please help

The call to the registerUser endpoint should work

Having an issue with a PDF Document not opening into a new tab for preview in javascript

I am working on a project that involves creating a PDF from automatically cropped images and a part I am working on is to simply have the newly created PDF open up in another tab for preview and download. The javascript file has the PDF Document called pdfDoc and I am not sure what to do make it open in a new tab. This part of a controller file using jsqrCode.

This is the constant for the PDF I am trying to open in a new tab.

const pdfDoc = await PDFDocument.create()

My amateur attempt getting that pdf to open in a new tab.
window.open(pdfDoc);

expiration date of a JWT token

I have a problem with a JWT token in JS, the question is very simple, I am creating a token as follows

const token = jwt.sign({ usernameCredential }, chave, { expiresIn: "15s" });

I receive this token and store it, after that when validating it, after the expiration date

function verificarToken(req, res, next) {
const token = req.headers.authorization; 

if (!token) {
    return res.status(401).json({ message: 'Token não fornecido' });
}

jwt.verify(token, chaveSecreta, (err, decoded) => {
    if (err) {
        console.log(err);
        return res.status(401).json({ message: 'Token inválido ou expirado' });
    } else {
        req.decoded = decoded;
        next();
    }
});

}

it always remains valid
How to adjust this?

Pass docker environment-vars to vite(svelte) docker-compose stack

I am trying to get docker-compose to properly pass my env vars to my svelte(kit) app running on vite.

https://github.com/dafeist-github/SongRex/commits/main/

On the link above, you can see any possible solution I have tried and found on the internet so far. None of them worked. How can I solve this?

const hosturl = (import.meta.env.VITE_SERVER_HOST || “server”) + “:3000”;

I just want to import this ENV-VAR to my app over docker-compose

Primevue ContextMenu inside v-for loop not working

I have the following vue code using PrimeVue.
I’m currently following this tutorial ContextMenu

<!-- Vue Component -->
<script>
    const dt = ref()
    const cm = ref()
    const data = ref([
        {id: 1, col1: 100, col2: 'foo', ...},
        {id: 2, col1: 200, col2: 'bar', ...},
        ...
    ])
    const selectedData = ref()
    const menuModel = ref([
        { label: 'Edit', icon: 'pi pi-fw pi-pencil', command: () => console.log('edit') },
        { label: 'Delete', icon: 'pi pi-fw pi-times', command: () => console.log('delete') }
    ])

    function onRowContextMenu (event) {
        cm.value.show(event.originalEvent)
    }
</script>

<template>
    <!-- OTHER STUFF HERE -->
    <ContextMenu ref="cm" :model="menuModel" @hide="selectedData= null" />
    <DataTable :value="data" ref="dt" dataKey="id" contextMenu v-model:contextMenuSelection="selectedData" @rowContextmenu="onRowContextMenu" >
        <Column>...</Column>
        ...
    </DataTable>
    <!-- OTHER STUFF HERE -->
</template>

The code above is working fine, but when i tried to wrap <ContextMenu> and <DataTable> inside <template> like this (below).

<!-- Vue Component -->
<script>
    // SAME AS ABOVE
    const menus = ref([
        { header: 'h1', label: 'lab1', ... },
        { header: 'h2', label: 'lab2', ... },
        ...
    ])
</script>

<template>
    <!-- OTHER STUFF HERE -->
    <template v-for="(menu, index) in menus" :key="index">
        <ContextMenu ref="cm" :model="menuModel" @hide="selectedData= null" />
        <DataTable :value="data" ref="dt" dataKey="id" contextMenu v-model:contextMenuSelection="selectedData" @rowContextmenu="onRowContextMenu" >
            <Column>...</Column>
            ...
        </DataTable>
    </template>
    <!-- OTHER STUFF HERE -->
</template>

Suddenly, it returns an error, Uncaught TypeError: cm.value.show is not a function. Any idea why this happened, and how to fix it?

Btw, for context, menus inside v-for is just a simple array to create multiple <DataTable> with <ContextMenu>.

Sharing auth session between SPA and Chrome extension

I have a React application and a Chrome extension. Authentication is currently implemented within the SPA. Now, I want to extend this authentication functionality to my Chrome extension seamlessly, without requiring users to manually log in to the extension. Is there a correct way to do this without the use of cookies?

Would I need to send my Bearer token to the Chrome extension through messages? –

Here is a sample code –

function Callback() {
  const { accessToken, setAccessToken } = useAuth();

  const navigate = useNavigate();
  const [searchParams, _] = useSearchParams();

  const sendTokenToExtension = (access_token: string) => {
    const extensionId = "";
    // chrome.runtime.connect(extensionId, { name: "example" });
    chrome.runtime.sendMessage(extensionId, access_token); <----- This does not work, Chrome is not defined error
  };

  useEffect(() => {
    (async () => {
      try {
        const response = await axios.get(
          `http://127.0.0.1:8000/auth/github/callback`,
          {
            params: {
              state: searchParams.get("state"),
              code: searchParams.get("code"),
              scope: searchParams.get("scope"),
              prompt: "consent",
            },
          }
        );

        if (response.status === 200) {
          setAccessToken(response.data.access_token);
          sendTokenToExtension(response.data.access_token);
          navigate("/dashboard");
        }
      } catch (error) {
        console.error("Error:", error);
      }
    })();
  }, []);

  return <>Redirecting now..</>;
}

export default Callback;

The code below is where I would set the accessToken to my secure local storage –

background.ts

console.log("Starting auth-listener..")

chrome.runtime.onMessageExternal.addListener(
  (request, sender, sendResponse) => {
    console.log("Received message from " + sender + ": ", request)
    sendResponse({ received: true }) //respond however you like
  }
)

Will sending the accessToken via messages be a security risk? is there a better way to do this?

How to implement event delegation

So I have a partial named (action-request-partial) that I created that loads dynamically into another partial(center). The thing is I want to be able to upload files from each of those partials (action-request partial) but my issue is that the javascript I have only responds to the input file field in the first dynamically loaded (action – request partial) I read online about event delegation but I don’t understand it enough to implement it. Here’s my code if any of you can help figure out a solution ? `

<div class="uw-actions-tab-display">
    <div class="uw-section" id="assigned_section">
      
      <label for="assigned-to-value">Assigned to: </label>
      <p id="assigned-to-value"><%= action.assigned_to_username %></p>
      <label for="supervisor-value">Supervisor: </label>
      <p id="supervisor-value"><%= action.created_by_username %></p>
      <label for="date_created">Created on: </label>
      <p id="date_created"> <%= action.created_on %></p>
      <label for="date_due">Due On: </label>
      <p id="date_due"><%= action.due_date %></p>
      <p id = "uw-id"><b> Id:</b> <%=action.uw_action_id %></p>
      
      
    </div>
    <div class="uw-section" id="request_type_section">
      <label for="Request Type">Request Type: </label>
      <p id="request_additional_docs" class = "request_type_docs"> </a>*Additional Documents <%= action.additional_documents %> </p>
      <p id="request_endorsement_docs" class = "request_type_docs"> *Endorsements <%= action.endorsements %></p>
      <p id="request_home_ownership_docs" class = "request_type_docs"> *Proof of Home Ownership <%= action.proof_of_home_ownership %></p>
      <p id="request_drivers_license_docs" class = "request_type_docs"> *Drivers License <%= action.drivers_license %></p>
      <p id="request_fl_license_check" class = "request_type_docs"> *FL DL CHECK <%= action.fl_dl_check %></p>
      <input type ="file" multiple id = "request_type_upload"></input> 
      <button type = "button" id = "request_type_section_upload_btn">Submit</button>
      
    </div>
    <div class="uw-section" id="uploaded_section">
      <label>Uploaded: </label>
      <p id="uploaded_additional_docs" class = "uploaded_docs" >*Additional Documents <%= action.additional_documents %> </p>
      <p id="uploaded_endorsement_docs" class = "uploaded_docs" >*Endorsements <%= action.endorsements %></p>
      <p id="uploaded_home_ownership_docs"  class = "uploaded_docs" >*Proof of Home Ownership <%= action.proof_of_home_ownership %></p>
      <p id="uploaded_drivers_license_docs"  class = "uploaded_docs">*Drivers License <%= action.drivers_license %> </p>
      <p id="uploaded_fl_license_check"  class = "uploaded_docs">*FL DL CHECK <%= action.fl_dl_check %></p>
     
      
    </div>
    <div class="uw-section" id="status_section">
      <label>Satus: </label>
      <p id="completed_status">*Completed</p>
      <p id="in_progress_status">*In Progress</p>
      <p id="t_docs_status">*T-Docs <br> Received</p>
      <p id="requested_status">*T-Docs <br> Requested</p>
    </div>
  </div>```
const requestTypeDocumentSubmitBtn = 

document.getElementById('request_type_section_upload_btn');
const uwActionID = document.getElementById('uw-id').innerText;

document.addEventListener('click', event => {
  if (event.target && event.target.id === 'request_type_section_upload_btn') {
      const requestTypeUploadedDocs = document.getElementById('request_type_upload').files;
      const formData = new FormData();
      const uwActionID = document.getElementById('uw-id').innerText;

  Array.from(requestTypeUploadedDocs).forEach(document => {
      if (document.name.includes("additional documents")) {
          formData.append('additional_documents', document);
          console.log('additional documents received');
      } else if (document.name.includes("proof of ownership")) {
          formData.append('proof_of_ownership', document);
          console.log('proof of ownership received');
      } else if (document.name.includes("endorsements")) {
          formData.append('endorsements', document);
          console.log('endorsements received');
      } else if (document.name.includes("drivers license")) {
          formData.append('drivers_license', document);
          console.log('drivers license received');
      }
      console.log(uwActionID);
  });

  fetch('/upload_documents', { 
      method: 'POST',
      body: formData
  })
  .then(response => {
      console.log('Server Responded !');
      console.log(response);
  })
  .catch(error => {
      console.error(error);
  });

}
}); “`

JavaScript Focus Ring Option Is Not Working

I’m using the code below to set focus to a button and have a focus ring displayed around the button. While the button does indeed get focus (which I can tell because if I press the space bar the button’s onclick event fires), the focus ring does not display (unless I manually tab to the button).

Thinking I was doing something wrong, I checked the example used in mdn web docs, and sure enough, it doesn’t work there either! (Scroll down to the JavaScript section and click play and you’ll see what I mean.)

Since I am using the latest and greatest version of Chrome for Windows, does that mean the focusVisible option is no longer supported? Or am I doing something wrong?

My code:

document.getElementById("myButton").focus({ focusVisible: true });

Controller verification not working/value being read as null when it is not

I am trying to verify that there is pre-existing entry in the row of a data table before updating its value. This is working for all of my functions except for the one present in a modal that should be adding the final values to the current row.
This is the controller for the salido function.

    public function salido($id)
    {
        $entity = $this->biometricosService->where('id', $id)->first();
        debug_to_console('salido');
        if ($entity->salido == null) {
            $data = $this->biometricosService->update($entity);
            return created_responses('data', ['message' =>  'Actualizacion de registro exitosa', 'data' => $data]);
        } else {
            return created_responses('data', ['message' =>  'No puede volver a timbrar para salido', 'code' => 400]);
        }
    }

and the function within a modal that calls it.

salido() {
            try {
                alert('Salir?');

                const currentTime = new Date().toLocaleTimeString();
                const id = localStorage.getItem('id_timbrada');

                axios.patch(`/masterdata/biometricos/salido/${id}`, {
                    salido: currentTime,
                    description: this.inputs.description,
                    location: this.inputs.location,
                    // total: th
                })
                    .then(response => {
                        if (response.data.code == 400) {
                            this.$toastr.e(response.data.message);
                        }
                        console.log('Timbrada exitosa:', response.data.data);
                        this.$toastr.s(response.data.message);
                        this.$hub.$emit('reload-' + this.tableId);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

            } catch (error) {
                console.error('Error posting data:', error);
            }
        },

As shown I would like the controller to return an error code if an entry has already been made in the salido column of that row which would then be caught by the salido js function and communicated to the user. What is extra baffling about this not working is that I have almost the exact same thing for some of my other functions. Take regreso for example.

public function regreso($id)
    {
        $entity = $this->biometricosService->where('id', $id)->first();
        if ($entity->regreso == null) {
            $data = $this->biometricosService->update($entity);
            return created_responses('data', ['message' =>  'Actualizacion de registro exitosa', 'data' => $data]);
        } else {
            return created_responses('data', ['message' =>  'No puede volver a timbrar para regreso', 'code' => 400]);
        }
    }

regreso() {
            try {
                alert('Regresar?');

                const currentTime = new Date().toLocaleTimeString();
                const id = localStorage.getItem('id_timbrada');

                axios.patch(`/masterdata/biometricos/regreso/${id}`, {
                    regreso: currentTime
                })
                    .then(response => {
                        if (response.data.code == 400) {
                            this.$toastr.e(response.data.message);
                        }
                        console.log('Timbrada exitosa:', response.data.data);
                        localStorage.setItem('regreso', response.data.data.regreso)
                        this.$toastr.s(response.data.message);
                        this.$hub.$emit('reload-' + this.tableId);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

            } catch (error) {
                console.error('Error posting data:', error);
            }
        },

The only real differences, as far as I can tell, are that salido posts more than one value, which shouldn’t be a problem as I have other working functions that do that, and that salido occurs in a modal while regreso is in my main index. Any help is much appreciated!

Google translator cdn

i’m working on the HTML website i have google translator cdn i want to change the english language to another language that is also working fine in google page insights i got this error

Properly defines charset Error!
A character encoding declaration is required. It can be done with a tag in the first 1024 bytes of the HTML or in the Content-Type HTTP response header. Learn more about declaring the character encoding.
I have already added this charset encode meta tag

function googleTranslateElementInit() {
var translator = new google.translate.TranslateElement({ pageLanguage: ‘en’ }, ‘google_translate_element’);

setTimeout(function () {
var select = document.querySelector(‘.goog-te-combo’);
console.log(“Dropdown element:”, select);
select.value = ‘es’;
console.log(“Selected value:”, select.value); // Debugging: Check if value is set to ‘es’
select.dispatchEvent(new Event(‘change’));
console.log(“Change event dispatched”); // Debugging: Check if change event is dispatched
}, 10); // Increase timeout to 2 seconds for testing
}

<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

What’s the problem with the script that should print input value in console?

That’s the part of HTML code that uses input

<form class="text-field_icon">
                    <input type="text" placeholder="Enter town" id="input" class="text-field_input">
                    <button class="text-field_aicon btn-reset"></button>
</form>

Thats the JS script, which upon activating says Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

<script defer type="text/java/script"
        let input = document.querySelector('input');
        let form = document.querySelector('form');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            console.log(input.value);
        })
</script>

I’ve tried getting those elements by id, by class and I still see this error

LinkedIn development api integration for recruitment

I have given an task to integrate the LinkedIn developer APIs to our hr management app to facilitate our customers to add jobs,recieve application any idea on this iam not getting any resources and documentation getting difficult to understand
If anybody has done before can help me get started and also not really understanding difference between

1.apply connect
2.xml feed
3. Job posting api
4.recruitment system connect
5.linkedin easy apply

Session is not updating on server side in Next-Auth

callbacks:{
    async jwt({ token, user }) {
        return {...token, ...user}
    },

    async session({session, token, user}) {
        console.log("Token: ",token)
        session.user.token = token;
        return session;

    },

This is callback code for updating session and token. It is updating session in client side perfectly but not able to update on Server Side. There are only 3 value i am getting on server side {name, email and image}

I dont know how to fix this problem.