How can I fix this Node JS 500 (Internal Server Error)?

This is my app.js file inside the api folder. I have set it up to take in the form details from the Contact.js file and send an email using the nodemailer library. I have already deployed my site on Vercel.




require("dotenv").config();
const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
  service: 'gmail',
  host: "smtp.gmail.com",
  port: 587,
  secure: false,
  auth: {
    user: process.env.USER,
    pass: process.env.APP_PASSWORD,
  },
});

module.exports = async (req, res) => {
  if (req.method === 'POST') {
    const formDetails = req.body;

    const mailOptions = {
      from: {
        name: formDetails.firstName,
        address: formDetails.email
      },
      to: process.env.USER,
      subject: "Portfolio Form",
      text: `Name: ${formDetails.firstName}nEmail: ${formDetails.email}nPhone: ${formDetails.phone}nMessage: ${formDetails.message}`,
    };

    try {
      await transporter.sendMail(mailOptions);
      console.log('Email has been sent');
      res.status(200).json({ code: 200, message: 'Email sent successfully' });
    } catch (error) {
      console.error(error);
      res.status(500).json({ code: 500, message: 'Error in sending email' });
    }
  } else {
    res.status(405).json({ code: 405, message: 'Method Not Allowed' });
  }
};



this is my Contact.js file where the form is located :




import { React, useState } from "react";
import { Container, Row, Col } from "react-bootstrap";
import contactImg from "../assets/img/contact-img.svg";
import 'animate.css';
import TrackVisibility from 'react-on-screen';


export const Contact = () => {
  const formInitialDetails = { firstName: '', lastName: '', email: '', phone: '', message: '' }

  const [formDetails, setFormDetails] = useState(formInitialDetails);
  const [buttonText, setButtonText] = useState('Send');
  const [status, setStatus] = useState({});

  const onFormUpdate = (category, value) => {
    setFormDetails({ ...formDetails, [category]: value })
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    setButtonText("Sending...");
    let response = await fetch("/api/contact", {
      method: "POST",
      headers: { "Content-Type": "application/json;charset=utf-8", },
      body: JSON.stringify(formDetails),
    });
    let result = await response.json();
    setFormDetails(formInitialDetails);
    if (result.code === 200) {
      setStatus({ success: true, message: 'Message sent successfully! I will get back to you as sson as possible!'});
    } else {
      setStatus({ success: false, message: 'Something went wrong, please try again later.'});
    }
    setButtonText("Send");
  };

  return (
    <section className="contact" id="connect">
      <Container>
        <Row className="align-items-center">
          <Col size={12} md={6}>
            <TrackVisibility>
              {({ isVisible }) =>
                <img className={isVisible ? "animate__animated animate__zoomIn" : ""} src={contactImg} alt="Contact Me"/>
              }
            </TrackVisibility>
          </Col>
          <Col size={12} md={6}>
            <TrackVisibility>
              {({ isVisible }) =>
                <div className={isVisible ? "animate__animated animate__fadeIn" : ""}>
                <h2>Get In Touch</h2>
                <form onSubmit={handleSubmit}>
                  <Row>
                    <Col size={12} sm={6} className="px-1">
                      <input type="text" value={formDetails.firstName} placeholder="First Name" onChange={(e) => onFormUpdate('firstName', e.target.value)} />
                    </Col>
                    <Col size={12} sm={6} className="px-1">
                      <input type="text" value={formDetails.lastName} placeholder="Last Name" onChange={(e) => onFormUpdate('lastName', e.target.value)}/>
                    </Col>
                    <Col size={12} sm={6} className="px-1">
                      <input type="email" value={formDetails.email} placeholder="Email Address" onChange={(e) => onFormUpdate('email', e.target.value)} />
                    </Col>
                    <Col size={12} sm={6} className="px-1">
                      <input type="tel" value={formDetails.phone} placeholder="Phone No." onChange={(e) => onFormUpdate('phone', e.target.value)}/>
                    </Col>
                    <Col size={12} className="px-1">
                      <textarea rows="6" value={formDetails.message} placeholder="Message" onChange={(e) => onFormUpdate('message', e.target.value)}></textarea>
                      <button type="submit"><span>{buttonText}</span></button>
                    </Col>
                    {
                      status.message &&
                      <Row>
                        <p className={status.success === false ? "danger" : "success"}>{status.message}</p>
                      </Row>
                    }
                  </Row>
                </form>
              </div>}
            </TrackVisibility>
          </Col>
        </Row>
      </Container>
    </section>
  )
}



I have already tried to change up the module.exports line as I thought perhaps the error 500 was coming from there… I have also completely changed up my code and asked AI to help me out finding what the problem is to no avail. Please help 🙁

Voiceflow Google Sheets integration

I am trying to fetch some dummy tracking data for shipping for a client who is interacting with my webchat – Voiceflow. The user should be able to put in the tracking number, which will fetch the status of the package from Google Sheets and displayed on the webchat for them to know the status of the package.

My issue is that I am not able to display the requested info, but I can see that I have successfully triggered an API call to the google sheet. I can’t seem to get it to display the result collected by the variable on the chat. Keeps giving ‘0’ as the result instead of the info fetched by the variable.

I am pretty new to this, I would also be grateful to be pointed in the direction of some useful tutorials for Voiceflow. Thanks! 🙂

How to hide an element and all its children from screen readers?

How to hide an element and all its children from screen readers, as well as prevent access with the keyboard?

I’m working with accessibility and on the pages I’m maintaining there are advertising banners that, unfortunately, I can’t simply remove, so I need some way to make the screen reader not scroll past these banners.

I’ve already tried the negative tabindex and aria-hidden, but some elements within the advertising banner are still accessible through keyboard navigation

Why I cannot select the specific Game object?

So I want to increase my game which is select(you can se below), but unfortunately my selection not working it throws an exception.

gameController.js:

exports.increaseScore = async (req, res) => {
    const userId = res.userId;

    try {
        const game = await Game.findOne({ where: { userId: userId } }, { limit: 1, order: [['createdAt', 'DESC']] });
        game.score += 1;
        await game.save();
        res.status(200).json("Score increased successfully!");
    } catch (err) {
        res.status(400).json(err);
    }
};

gameModell.js:

const Game = sequelize.define("Games", {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        unique: true,
    },
    score: {
        type: Sequelize.INTEGER,
        allowNull: false
    },
    difficulty: {
        type: Sequelize.INTEGER,
        allowNull: false
    },
});

exports.Game = Game;

Relations between game and user:

const userModel = require('./models/user');
const gameModel = require('./models/game');

userModel.hasMany(gameModel.Game, { foreignKey: 'userId' });
gameModel.Game.belongsTo(userModel, { foreignKey: 'userId' });

Why i got always TypeError: NetworkError when attempting to fetch resource when running below js code?

enter image description hereI add event listener to the signup button as the image shows. But when executes both get and post http methods throw type error exception. Even i manage CORS exeception also.
But when i call function normally it works and also postman works well Can i have solution?The firefox browser shows TypeError: NetworkError when attempting to fetch resource.

When converting to PDF, how to keep “radio button” square instead of circle?

Background:
I am new to learning HTML and frontend development. Currently, I am working on creating an HTML form for users to input their information. First, I utilized an online free tool to convert an existing PDF form into HTML format. After the conversion process, I received several files, including .woff, .svg, .css, and HTML files. These files contained the necessary components for the form. One observation I made is that the user selection boxes are represented by files with the “.svg” extension. To tailor the form to our business requirements, I began customizing the HTML file.

Example:
This is a segment of the original PDF that needs to be replicated on the web form:
Original PDF

Below is a section of my form in the frontend view. Both question 8 and 9 require single selections from the user. The functionality works well, allowing users to enter and save data. When they check one of the boxes, it automatically unchecks the previously checked box, as it’s set up with “radio buttons” for single selection:
Web form

This is the html code for the above content mentioned, I’ll use question 8 as an example:

<!-- Section 8 Starts-->
                    <div class="stl_01" style="top:53.5943em; left:3em;">
                        <span class="stl_17 stl_08 stl_19" style="font-weight:bold;">8</span>
                    </div>
                    <div class="stl_01" style="top:53.5943em; left:3.42em;">
                        <span class="stl_17 stl_08 stl_19" style="font-weight:bold;">.</span>
                    </div>
                    <div class="stl_01" style="top:53.5943em; left:4.5em;">
                        <span class="stl_17 stl_08 stl_18" style="font-weight:bold; word-spacing:0.0016em;">Business Ownership Ethnicity: &nbsp;</span>
                    </div>
                    <div class="stl_01" style="top:54.5543em; left:5.835em;">
                        <span class="stl_07 stl_08 stl_23" style="word-spacing:0.0009em;">African American or Black (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="African American or Black"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:55.5143em; left:5.835em;">
                        <span class="stl_07 stl_08 stl_37" style="word-spacing:-0.0013em;">American Indian or Alaskan Native (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="American Indian or Alaskan Native"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:56.4693em; left:5.835em;">
                        <span class="stl_07 stl_08 stl_29" style="word-spacing:-0.0057em;">Asian (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Asian"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:54.5543em; left:22.3817em;">
                        <span class="stl_07 stl_08 stl_26" style="word-spacing:0.0009em;">Hispanic or Latino (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Hispanic or Latino"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:55.5143em; left:22.3817em;">
                        <span class="stl_07 stl_08 stl_28" style="word-spacing:0.0024em;">Native Hawaiian or other Pacific Islander (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Native Hawaiian or other Pacific Islander"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:56.4693em; left:22.3817em;">
                        <span class="stl_07 stl_08 stl_34" style="word-spacing:-0.0031em;">Multi-ethnic minority ownership (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Multi-ethnic minority ownership"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:57.4309em; left:22.3817em;">
                        <span class="stl_07 stl_08 stl_18" style="word-spacing:-0.001em;">Multi-ethnic ownership (50% Minority – 50% Non-Minority) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Multi-ethnic ownership"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:58.3909em; left:22.4067em;">
                        <span class="stl_07 stl_08 stl_37" style="word-spacing:0.0002em;">Decline to state &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Decline to state"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:57.4309em; left:5.84em;">
                        <span class="stl_07 stl_08 stl_38" style="word-spacing:-0.002em;">Caucasian / White (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Caucasian / White"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <div class="stl_01" style="top:58.3909em; left:5.84em;">
                        <span class="stl_07 stl_08 stl_28" style="word-spacing:0.0025em;">Filipino (&gt; 50%) &nbsp;</span>
                        <input type="radio" class="input checkbox" name="ethnicity"
                               value="Filipino"
                               style="left: -1.28em;top: 0.07em;"
                               required>
                    </div>
                    <!-- Section 8 Ends-->

This is JavaScript code for converting webform to PDF and sending to the designated email after user filled in data:

function exportPdf() {
        return new Promise((resolve) =>{
            loadData.then(() =>{
                const element = document.querySelector('.container');
                const pdfOptions = {
                    pagebreak: { mode: 'avoid-all', after: '.stl_02' },
                    margin: 0, 
                    filename: 'output.pdf',
                    image: { type: 'jpeg', quality: 0.98 },
                    html2canvas: { scale: 2 }, 
                    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
                };
                html2pdf().from(element).set(pdfOptions).output().then(binaryString =>{
                    
                    const binaryArray = new Uint8Array(binaryString.length);
                    for (let i = 0; i < binaryString.length; i++) {
                        binaryArray[i] = binaryString.charCodeAt(i);
                    }
                    
                    const blob = new Blob([binaryArray], { type: 'application/pdf' });
                    
                    const pdfFile = new File([blob], 'output.pdf', { type: 'application/pdf' });
                    resolve(pdfFile)
                })
            })
        })
    }

My problem:
The workflow appears to be functioning correctly: the user enters data and clicks a button labeled ‘Save and Send.’ The web form is then generated in PDF format and sent as an attachment to the designated email. However, upon opening the attachment in the email, sections 8 and 9 in the PDF appear as follows:

enter image description here

The square checkboxes have transformed into round radio buttons, and the user selections are not reflected in the PDF. Although I understand that radio buttons are what I used in HTML, I still want the document to display square boxes, as shown on the website.

I would greatly appreciate any assistance on these matters. Thank you!

To supplement my question, this is the sendEmail function in the related controller class:

@PostMapping("/send-email")
    public AjaxResult sendEmail(@RequestBody List<String> filenames) throws MessagingException, IOException {
        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Map<String, File> fileMap = new HashMap<>();
        List<String> names = Arrays.asList("vendorForm.pdf");
        for (int i = 0; i < filenames.size(); i++) {
            File file = new File(URLDecoder.decode(uploadPath, StandardCharsets.UTF_8) + File.separator + filenames.get(i));
            String filename = "";
            if (i < names.size()){
                filename = names.get(i);
            }else {
                filename = filenames.get(i);
            }
            fileMap.put(filename, file);
        }
        emailService.send(fileMap, securityUser.getUser().getEmail());
        return AjaxResult.ok();
    }

my chart-js dosen’t show up how can i show a chart

I want to select a start date and an end date. to display data in a graph based on the selected range. but it doesn’t work in MyShopexpressChart

Example my index.php

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chart</title>
</head>
<body>

<center>
   <form method="GET" action="">

        <label for="start_date">start date:</label>
        <input type="date" id="start_date" name="start_date" >

        <label for="end_date">end date:</label>
        <input type="date" id="end_date" name="end_date" >

        <input type="submit" value="search">
        
    </form>

    <span><canvas id="myExpressChart"></canvas></span> 
    <span><canvas id="myShopexpressChart"></canvas></span> 


</center>


<script>

    
          fetch('data_express.php?start_date=<?= $start_date ?>&end_date=<?= $end_date ?>')
            .then(response => response.json())
            .then(data => {
                // Extract labels and values from data
                var labels = data.map(item => item.category);
                var values = data.map(item => item.value);

                // Create a bar chart
                var ctx = document.getElementById('myExpressChart').getContext('2d');
                var myBarChart = new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: values,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)',
                                'rgba(255, 206, 86, 0.2)',
                                'rgba(75, 192, 192, 0.2)',
                                'rgba(153, 102, 255, 0.2)',
                                'rgba(255, 159, 64, 0.2)',
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)'
                            ],
                            borderColor: [
                                'rgba(255, 99, 132, 1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)',
                                'rgba(255, 99, 132, 1)',
                                'rgba(54, 162, 235, 1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                });
            })
            .catch(error => console.error('Error fetching data:', error));



    fetch('data_shopexpress.php?start_date=<?= $start_date ?>&end_date=<?= $end_date ?>')
        .then(response => response.json())
        .then(data => {
            // Extract labels and values from data
            var labels = data.map(item => item.category);
            var values = data.map(item => item.value);

            // Create a bar chart
            var ctx = document.getElementById('myShopexpressChart').getContext('2d');
            var myBarChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)',
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)',
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        })
        .catch(error => console.error('Error fetching data:', error));
</script>

</body>
</html>

myExpressChart is work. but myShopexpressChart dosen’t work. I dont know why

data_express.php

<?php

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "nupost1"; 


$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$date_filter = "AND created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";

$sql = "SELECT 
            CASE parcel_express
                WHEN 1 THEN 'ไปรษณีย์'
                WHEN 2 THEN 'Kerry'
                WHEN 3 THEN 'Ninja Van'
                WHEN 4 THEN 'J&T'
                WHEN 5 THEN 'FLASH'
                WHEN 6 THEN 'DHL'
                WHEN 7 THEN 'SPX'
                WHEN 8 THEN 'LEX'
            END AS express_name,
            COUNT(*) AS express_count 
        FROM parcel WHERE 1 $date_filter
        GROUP BY parcel_express";

$result = $conn->query($sql);

$express_data = array();


if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $express_item = array(
            "category" => $row["express_name"],
            "value" => $row["express_count"]
        );

        array_push($express_data, $express_item);
    }
} else {
    echo "0 results";
}

$conn->close();


echo json_encode($express_data);
?>

data_shopexpress.php

<?php

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "nupost1"; 


$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$date_filter = "AND created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";


$sql = "SELECT 
            CASE receipt_express
                WHEN 1 THEN 'ไปรษณีย์'
                WHEN 2 THEN 'Kerry'
                WHEN 3 THEN 'Ninja Van'
                WHEN 4 THEN 'J&T'
                WHEN 5 THEN 'FLASH'
                WHEN 6 THEN 'DHL'
                WHEN 7 THEN 'SPX'
                WHEN 8 THEN 'LEX'
            END AS express_name,
            COUNT(*) AS express_count 
        FROM receipt WHERE 1 $date_filter
        GROUP BY receipt_express";

$result = $conn->query($sql);

$express_data = array();

if ($result->num_rows > 0) {
    
    while($row = $result->fetch_assoc()) {
        $express_item = array(
            "category" => $row["express_name"],
            "value" => $row["express_count"]
        );
        array_push($express_data, $express_item);
    }
} else {
    echo "0 results";
}

echo json_encode($express_data);
?>

I want to select a start date and an end date. to display data in a graph based on the selected range. but it doesn’t work in MyShopexpressChart

This is my SQL database

table parcel

CREATE TABLE `parcel` (
  `parcel_ID` int(255) NOT NULL,
  `tracking_number` varchar(20) NOT NULL,
  `parcel_sender` int(255) NOT NULL,
  `parcel_receiver` int(255) NOT NULL,
  `parcel_rider` int(255) NOT NULL,
  `parcel_type` varchar(255) NOT NULL,
  `parcel_express` int(255) NOT NULL,
  `parcel_status` varchar(255) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `parcel_receivetime` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

table receipt

CREATE TABLE `receipt` (
  `receipt_ID` int(11) NOT NULL,
  `receipt_product` int(11) NOT NULL,
  `receipt_amount` int(11) NOT NULL,
  `receipt_express` int(11) NOT NULL,
  `receipt_total` int(11) NOT NULL,
  `receipt_ridername` varchar(255) NOT NULL,
  `receipt_ridersex` int(11) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

I tried to ask CHATGPT but it didn’t work to show the MyShopexpressChart graph. Hope everyone reading this post can help me and thank you very much if you help me.

I need to showup my javascript Chart in website php.

Vue Router: Browser navigation button back not working

In my Vue App i use the vue router to computed navigate from a create page to edit page.

The use case:

  • create a ressource
  • on success go to edit page

The use case above works fine.

Further use case:

  • click on the button browser back

Expected: default create page content (create form)
Actual: Route has changed, content remains (edit form)

So it seems, the router history fails.

router/index.ts

import {createRouter, createWebHashHistory} from 'vue-router';
...
import testRoute from  './test_route'

const routes = [
  ...
  testRoute
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

export default router;

router/test_r
oute/index.ts

import TestPage from "@/module/test/page";
...
import TestDetail from "@/module/test/view/detail";

const route = {
    component: TestPage,
    path: "/test/page",
    redirect: ...,
    children: [
        ...,
        {
            path: 'create-test', 
            name: "testDetailCreate",
            component: TestDetail
        },
        {
            path: 'edit-test/:id?', 
            name: "testDetailEdit",
            component: TestDetail
        }
    ]
}

export default route;

~/detail/index,ts

export default defineComponent({
  ...
  methods: {
    ...,
    createHandling() 
      {
        ...
        fetch("%create-resource%", {
          ...
        }).then((resp) => {
          ...
          return resp.json()
        }).then(data => {
          // set store vars
          ...
          this.$router.push({name: 'testDetailEdit', params: {id: data.id}});
          // location.href = "/edit-test/" + data.id;
          // location.reload()
        })
      },
  }
})

I try above code with location.href and this.$router.push, both with the same unexpected result.

So my question is, why the vue router history doesn’t work within the browser navigation?

Do I need to use nodejs https module if my host provider provides TLS Certificates?

It is my first time of deploying an application that would be used in real life and it uses stripe api for handling payments. I would like to deploy the nodejs application on render host. Render said this: “All applications and static sites hosted on Render come with fully managed and free TLS certificates. There is no setup and you don’t need to do anything at all; everything just works out of the box…” I want to know if I would still need to use the nodejs https module instead of http module to handle the requests.

Redirect for login to different origin without disrupting the current page

I’m having a challenging design issue that’s bumping into the security limitations of browsers.

I’m working on a site that presently uses Username and Password. The front end, every few seconds, makes a JavaScript based “session maintenance” call to the server to validate their session is still valid. If not, the front end one covers their work with an opaque div with a username/password popup for them to revalidate their credentials. Submission is done with JavaScript, and a JSON response. When correct, the opaque div disappears and their work is still sitting there with any pending changes they’ve made.
(The opaque div is not meant to be a security measure)

I’m rewriting this to work with a certificate instead, but the validation is done with a site having a different origin. When a user requests a page, the host checks if they have provided a valid certificate. If not, the host redirects them to a different page to validate credentials. Once done the host redirects them back to my page, and staples their certificate information for me into the HTTP Request header.

I’d like to implement this new method similarly. Specifically, they’re on my page doing work, the session timer expires so an opaque window covers their work with a popup telling them they need to revalidate. Then the opaque div disappears and their work is still sitting there.

How to detect the need to revalidate, and how to get a signal to the original window showing the validation is complete is the problem.

When my session maintenance call is sent to the server, I think instead of getting a JSON message back with a true/false, I will now get a true when they have a good session, or an HTML response from the redirected host page if they are no longer logged in. I’m pretty sure I can use this to pop up the opaque div.

New Tab:

From there I first thought, I’ll just have a “login” button on the opaque div that the user can click. It would open a new tab pointing to one of my pages, which would get redirected to the host page. They’d revalidate and get sent back to some other page of mine. The original tab could monitor that that page to show up in the URL of the new tab.

  revalidate() {
     this.newTab = window.open("random_page.php", "_blank");
  }
  checkValidated() {
     console.log(rootUrl);
     if (this.newTab.location.href == rootUrl + "random_page.php") {
        alert("You are logged in");
        //remove opaque div and whatever else here
     }
  }

The host page isn’t on the same-origin so I can’t see it’s url from my original tab, but I hoped once it finally redirected back to my page on the same-original that I’d be able to see it. Not the case, as soon as the tab leaves the origin the access is shut down and never given back.

Monitor for session creation:

This idea would leverage the existing session maintenance check that the front end already does. So when the session maintenance makes its call to the server and discovers the session has ended, it does the opaque DIV with the “login” button. Then it immediately starts calling the session maintenance thing every second or two testing for it to be valid again. The user hits login, they get the new tab and revalidate. The page they’re directed to just shows them “close this tab and return to your original tab”. The original tab is stil making it’s session maintenance calls and gets an affirmation from the server that their session is valid, so it drops the opaque div.

I think this would work, and it leverages the existing session maintenance call so it would be a quick fix, but it seems like a sloppy user experience.

Monitor Cookies:

Another thought was to send a “completed” message to the original tab through a cookie. I’ve not really messed with cookies much so I’m not sure about this. So, the mainpage.php in the main tab, would open validate.php in a new tab. The mainpage.php would then set an interval to keep checking a cookie named “completed” to be set to true. After the host revalidates the user’s account and redirects to validate.php that script will set the “completed” cookie. Mainpage.php sees that and drops the opaque div.

This would still require the user to close that second tab. Also if the user revalidated in some other way then the original tab would still be sitting there, unless I made every entry point set the cookie.

iFrame:

mainpage.php, instead of popping up the opaque div, it puts an iframe in front of the content and navigates to validate.php. The user gets redirected, logs in, and eventually ends up at my validate.php. That page removes the iframe from the main page by sending some javascript like this:

window.parent.document.getElementById('revalidation-iframe').hidden = true

This seems like a really smooth experience for the user, but I’m not yet sure if the host is going to allow cross origin requests like this.

I’m really scratching my head about the best way to proceed with this. I’m hoping someone has some ideas I haven’t thought of, or can point out pitfalls that I need to be aware of.

Web telemetry attribution – Well architected framework reference [closed]

I have an application that can be greatly customized by users, by adding the modules they want, drag and drop elements, run custom scripts etc.
I want to create a telemetry package that will differentiate between what comes as a platform activity vs what comes as customization activity.
There is very less reference designs online on designing a telemetry tracking system for the web that will help analyze performance, attribute it in a browser context.

Cannot GET/”url” error when refreshing the page

Im currently working on react app with vite and express.There is no problem when i go to url from home page but when i refresh it on the url i get the Cannot GET/users error.

I find this code block for solution

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
})

but when i pass my index.html file Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. this error appears on console please help.

Flatlist not rendering in react native app

const Popularjobs = () => {
  const router = useRouter();

  const { data, error, isLoading } = useFetch("search", {
    query: "React developer",
    num_pages: "1",
  });

  console.log("Console log from popular job");
  return (
    <View style={styles.cardsContainer}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Popular Jobs</Text>
        <TouchableOpacity>
          <Text style={styles.headerBtn}>Show All</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.cardsContainer}>
        {isLoading ? (
          <ActivityIndicator size={"large"} color={COLORS.primary} />
        ) : error ? (
          <Text>Something went wrong</Text>
        ) : (
          <FlatList
            data={data}
            renderItem={({ item }) => <PopularJobCard item={item} />}
            keyExtractor={(item) => item?.job_id}
            contentContainerStyle={{ columnGap: SIZES.medium }}
            horizontal
          />
        )}
      </View>
    </View>
  );
};

export default Popularjobs;

Is it the bug of new react-native version?

The FlatList is not rendering at all when i pass the data fetched from api but it does get render when i use dummy data my react native version is 0.73

Trouble with dynamic cron job scheduling based on activity

I’ve got a cron.schedule function here that runs the code once every second. When the user is on the website, it displays “In website” and when they enter a game, it shows “In game” However, when the user is in the game, it stops the cron.schedule, so the code doesn’t run every second when the user returns to the website. Any help will be appreciated.

The checkGameStatus() function returns either true or false. true being in the user is in the website, false being the user being in game.

let task = cron.schedule("* * * * * *", async () => {
    let isWebsite = await checkGameStatus();
    if (isWebsite) {
        task.start();
        console.log("In website")
    } else {
        task.stop();
        //ipcRenderer.send("trackgame", game, placeid)
        console.log("In game")
    }
});

Any help will be appreicated!

Generic type for raw JSON data

I have a script that makes a request to my API and returns the response to the caller. I’m struggling to type it up.

Responses from the API always have two properties – a boolean success flag indicating the state of the response, and either a data property containing the requested data or an errors property containing one or more errors. My initial attempt at typing is as follows

type ApiResponse<T> = {
    success: true;
    data: T
} | {
    success: false;
    errors: string[]
}

However, when I went to use this to retrieve an Event, I found a problem: the returned data doesn’t match the type I pass in, due to how JSON is encoded over the wire. Here’s the type for an Event:

type Event = {
    id: string;
    name: string;
    start: Date;
    end: Date;
    visibility?: {
        host: boolean,
        bands: boolean,
        public: boolean
    }
}

Vs a sample response:

{
    "success": true,
    "data": [
        {
            "id": "70a1567f-5d5d-4c25-8622-f0cea9b67056",
            "name": "Test Event",
            "start": "2024-02-18T23:00:00.000Z",
            "end": "2024-02-18T23:01:00.000Z",
        },
    ]
}

As you can see, the dates have been string encoded to make it easier to pass over the wire. I read through the JSON spec and noticed everything should be stringified except for numbers, strings, booleans, nulls, objects, and arrays.

With this in mind, I attempted to modify my ApiResponse so that the caller knew the values were stringified and that they would need to unpack them. However, I can’t quite seem to figure out where I’m going wrong with the type mapping. Here’s the latest mapping I have:

type Stringified<T> = {
    [key in keyof T]: T[key] extends number ? number : 
                      T[key] extends boolean ? boolean :
                      T[key] extends Array<unknown> ? Stringified<T[key]> :
                      T[key] extends object ? Stringified<T[key]> :
                      string
}

type ApiResponse<T> = {
    success: true;
    data: Stringified<T>
} | {
    success: false;
    errors: string[]
}

However, this doesn’t give the expected result for ApiResponse<Event>. Intellisense is taking the type hinting that they are Stringified<Date> instead of just string, and the visibility is being treated as type string when it should be Stringified<{host: boolean, bands: boolean, public: boolean}>. I think it may be to do with the line T[key] extends object, but I’ve tried various permutations here and can’t seem to find one that works (Object, {}, Record<unknown, unknown>)

These errors are showing when I’m trying to hydrate the strings back into proper objects like so:

function hydrateEvent(rawEvent: Stringified<Event>){
    const event: Event = {
        id: rawEvent.id,
        name: rawEvent.name,
        start: new Date(rawEvent.start),
        end: new Date(rawEvent.end)
    };

    if(rawEvent.visibility){
        event.visibility = rawEvent.visibility;
    }

    return event;
}

Is what I’m trying to do not possible, or am I missing something obvious?