Why am I getting a JSON error and how do I fix it

I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database

The table code is this

  <div class="superhero">
    <h1>Lets add our first name </h1>
    <form action="/add_user" method="post">
        <input type = "text" firstname = "firstname">
    <h1>Lets add our last name </h1>
    <form action="/add_user" method="post">
        <input type = "text" lastname = "lastname">
        <input type="submit" class="btn btn-primary">
    </form>

Then this is taken into the nodeJS server with this command

app.post('/add_people', function(req, res){
    axios.get('http://127.0.0.1:5000/api/adduser')
    .then((response)=>{
        var restlist = response.data.results;
        console.log(restlist);
// Now we will execute the results in the page named thanks
    });
});

Then at the end it is going to be taken to the RestAPI with that is using this route

@app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
    request_data = request.get_json() # Gets the info from the table and converts to JSON format
    new_fname = request_data['firstname']
    new_lname = request_data['lastname']
    conn = create_connection("", "", "", "")
    sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
    execute_query(conn, sql) # This will execute the query
    return 'Post worked'

Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I’ve been trying to find out how to do this for sometime with no luck.

UDATE: I later changed the two items as suggested. The route is

app.post('/add_people', function(req, res){
    axios.post('http://127.0.0.1:5000/api/adduser')
    .then((response)=>{
        var restlist = response.data.results;
        console.log(restlist);
// Now we will execute the results in the page named thanks
    });
});

and the form is now

        <form action="/add_people" method="post">
            <input type = "text" firstname = "firstname">
        <h1>Lets add our last name </h1>
            <input type = "text" lastname = "lastname">
            <input type="submit" class="btn btn-primary">
        </form>

I get the error that

  },
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

and also this error on the restAPI window

TypeError: 'NoneType' object is not subscriptable

Trying to show exact mount of days when select specific month

I was trying to create a form to select month and day. I want dynamically add the exact amount of days when a specific month is selected. But only the January, February, and April of months are selectable after running the switch statement. Can anyone pls help me?

html:

<select id="months" name="months">
            <option value='31'> January </option>
            <option value='28'> February </option>
            <option value='31'> March </option>
            <option value='30'> April </option>
            <option value='31'> May </option>
            <option value='30'> June </option>
            <option value='31'> July </option>
            <option value='31'> August </option>
            <option value='30'> September </option>
            <option value='31'> October </option>
            <option value='30'> November </option>
            <option value='31'> December </option>
        </select>

        <select id="days" name="days"></select>

js:

const $months = document.getElementById('months')

function dayOfMonthOne() {
    for (let i = 1; i < 32; i++) {
        const days = `
        <option>${i}</option>
        `
        const $days = document.getElementById('days')
        $days.innerHTML = $days.innerHTML + days
    }
}

function dayOfMonthZero() {
    for (let i = 1; i < 31; i++) {
        const days = `
        <option>${i}</option>
        `
        const $days = document.getElementById('days')
        $days.innerHTML = $days.innerHTML + days
    }
}

function dayOfMonthTwo() {
    for (let i = 1; i < 29; i++) {
        const days = `
        <option>${i}</option>
        `
        const $days = document.getElementById('days')
        $days.innerHTML = $days.innerHTML + days
    }
}

$months.addEventListener('change', function(){
    switch ($months.value) {
        case '31':
            $months.value = '31'
            dayOfMonthOne()
            break
        case '30':
            $months.value = '30'
            dayOfMonthZero()
            break
        case '28':
            $months.value = '28'
            dayOfMonthTwo()
            break
    }
})

Advantage of mapping with a async binding vs a concrete object in Angular?

Is there any advantage or benefit to using a async binding vs just mapping to a concrete object when my service call returns with data for my HTML page?

Here is an example of the two options.

  1. Map to a concrete object
// component
event: any;

// ngOnInit()
this.eventService.getEvent(this.id).pipe(take(1)).subscribe(response => {
  this.event = response;
}, error => {
  console.log(error);
});

// service
getEvent(id: number): Observable<any> {
  return this.http.get<any>(this.baseUrl + 'events/' + id);
}
<div>{{event.title}}</div>
<div>{{event.date}}</div>
  1. map to a async binding
// component
event$: Observable<any> = of (undefined);

// ngOnInit
this.event$ = this.eventService.getEvent(this.id).pipe(take(1),
  catchError(error => {
    console.log(error);
    return throwError(error);
  }));

// service
getEvent(id: number): Observable<any> {
  return this.http.get<any>(this.baseUrl + 'events/' + id);
}
<div>{{(event$ | async).title}}</div>
<div>{{(event$ | async).date}}</div>

Write after end error when launch server in nodejs

I am beginner at NodeJS and Im doing a “NodeJS and Express.js full course” at freecodecamp yt and I copied author code wich for him works perfectly but I got an error.

Code:


  const server = http.createServer((req, res)=> {
if(req.url === '/') {
  res.end('Home Page')
}
if(req.url === '/about') {
 res.end('About us')
}
res.end('Error')
})

server.listen(3000, ()=>{
  console.log('Server listening...');
})

Idk why He got home, about and error page when user go to wrong page it should throw “Error” text on page, but instead my program is throwing an error in nodeJS program:


events.js:377
    throw er; // Unhandled 'error' event
     ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (internal/errors.js:322:7)
    at writeAfterEnd (_http_outgoing.js:694:15)
    at ServerResponse.end (_http_outgoing.js:815:7)
    at Server.<anonymous> (C:UsersjonatDesktopnodejsapp.js:10:5)
    at Server.emit (events.js:400:28)
    at parserOnIncoming (_http_server.js:900:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:127:17)
Emitted 'error' event on ServerResponse instance at:
    at writeAfterEndNT (_http_outgoing.js:753:7) 
  at processTicksAndRejections (internal/process/task_queues.js:83:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}

Can someone explain this to me? I would be appreciate. Thank you in advance.

How to do update in AWS Dynamo DB using NodeJS

I have written this function to do update in dynamo table

const updateTask = async (req, res) => {
  try {
    const { existingTaskText,updatedTaskText } = req.body;
    console.log(existingTaskText,updatedTaskText );
    UPDATE({
      TableName: "todos",
      Key:{ task: existingTaskText},
      UpdateExpression:"set task = :task",
      ExpressionAttributeValues: {":task": updatedTaskText},
    });
    res.status(200).json({ data: "this is controller" });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

this is calling UPDATE

const UPDATE = async (payload) => {
  try {
    console.log(payload);
    const updateDoc = await dbClient
      .update({
        TableName: payload.TableName,
        Key: payload.Key,
        UpdateExpression: payload.UpdateExpression,
        ExpressionAttributeNames:payload.ExpressionAttributeNames,
        ReturnValues: "UPDATED_NEW",
      })
      .promise();
    console.log(updateDoc);
  } catch (error) {
    console.log(error);
  }
};

When I am testing this in postman, I am getting this error

ValidationException: Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: :task

this is payload log getting passed

{
  TableName: 'todos',
  Key: { task: 'see its  done' },
  UpdateExpression: 'set task = :task',
  ExpressionAttributeValues: { ':task': 'edited' }
}

Clickable date in full calendar

I am a beginner I downloaded full calendar 5.10.1 from fullcalendar.io. Here’s what I want to do. If I click on any date, it will go to my registration.html.

Here is calendar script:

document.addEventListener(‘DOMContentLoaded’, function() {
var calendarEl = document.getElementById(‘calendar’);
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: ‘dayGridMonth’
});
calendar.render();
});

Here is registration form:

    <fieldset>
      <legend>For person</legend>
      <label>
        Name
        <input type="text" name="name" required>
      </label>
      <div class="two-cols">
        <label>
          Email address
          <input type="email" name="email" required>
        </label>
        <label>
          Phone number
          <input type="tel" name="phone">
        </label>
      </div>
    </fieldset>

    <fieldset>
      <legend>Appointment request</legend>
      <div class="two-cols">
        <label>
          Datum
          <input type="date" name="Appointment request" required>
        </label>
        <div class="inline">
          <label>
            <input type="hidden" name="Morning desired" value="no">
            <input type="checkbox" name="Morning desired" value="yes">
            Morning
          </label>
          <label>
            <input type="hidden" name="Afternoon desired" value="no">
            <input type="checkbox" name="Afternoon desired" value="yes">
            Afternoon
          </label>
        </div>
      </div>
      <p>Confirmation requested by</p>
      <div class="inline">
        <label>
          <input type="radio" name="Confirmation requested by" value="email" checked>
          Email
        </label>
        <label>
          <input type="radio" name="Confirmation requested by" value="phone">
          Phone call
        </label>
      </div>
    </fieldset>
    
    <div class="btns">
      <input type="text" name="_gotcha" value="" style="display:none;">
      <input type="submit" value="Submit request">
    </div>

  </form>

Nuxt nested routing doesnt work 2 levels deep

I’m trying to build a Nested Page in Nuxt using this guide and this guide and running into a problem

What I want is:

  1. foobar.com/2021 shows me the parent page for the year
  2. foobar.com/2021/jun shows me the parent page content for the year + child page for the month
  3. foobar.com/2021/jun/edit shows me the parent page content for the year + the ‘edit’ child page for that month.

In the above cases, both the ‘2021’ part and the ‘Jun’ part will be dynamic

The problem:
I can get the first 2 to work but the not the edit route. This is what works currently:

/pages
_year.vue
_year/
_month.vue
index.vue

It’s demonstrated in this codesandbox here

What I’ve tried to get the edit route to work:
Add a _child folder under _year, right alongside _child.vue
Add a edit.vue there (didnt work)
Add a index.vue in addition (didnt work)
Rename the edit.vue to _edit.vue (didn’t work)

Is this something that’s feasible with automatic routing in Nuxt?

How do I conditionally render CSS with Material UI useStyles/makeStyles?

I’m trying to display the latestMessageText variable as bold and black if the props meet a certain condition. The useEffect method works, an ugly solution; How do I use Material UI’s useStyle hook to execute my goal. I’ve tried passing props to useStyle, using them inside the makeStyles function, to no effect.

import React, { useEffect, useRef } from "react";
import { Box, Typography } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    justifyContent: "space-between",
    marginLeft: 20,
    flexGrow: 1,
  },
  username: {
    fontWeight: "bold",
    letterSpacing: -0.2,
  },
  previewText: {
    fontSize: 12,
    // color: "#9CADC8",
    letterSpacing: -0.17,
    color: (messages, otherUser) => {
      if (messages.length && otherUser) {
        const lastMessage = messages[messages.length - 1];
        const { senderId, receiverHasRead } = lastMessage;
        if (senderId === otherUser.id && !receiverHasRead) {
          return 'black'
        }
        return "#9CADC8"
      }
    }
  },
  black: {
    color: 'black',
    fontWeight: 700,
  }
}));

const ChatContent = (props) => {
  const { conversation } = props;
  const { latestMessageText, otherUser, messages } = conversation;
  const classes = useStyles(messages, otherUser);

  return (
    <Box className={classes.root}>
      <Box>
        <Typography className={classes.username}>
          {otherUser.username}
        </Typography>
        <Typography className={classes.previewText}>
          {latestMessageText}
        </Typography>
      </Box>
    </Box>
  );
};

export default ChatContent;

How typing a selected object from a list of different objects?

I have an object that is going to have field products, this field will be filled with the response returned by different endpoints which each return a type of product. something like:

const products = {
  // each of this kind of products comes from endpoint response
  someProduct: {},
  someOtherProduct: {}
  anotherProduct: {}
}

I Can type all product types like this answer:

interface BaseProduct {
  name: string;
  description: string;
  price: number;
  type: string;
}

interface SomeProduct extends BaseProduct {
  genericAttrOne: string;
  genericAttrTwo: string;
}

interface OtherProduct extends BaseProduct {
  anAttributeOne: string;
  anAttributeTwo: string;
}

interface AnotherProduct extends BaseProduct {
  anotherAttributeOne: string;
  anotherAttributeTwo: string;
}

type Product = SomeProduct | OtherProduct | AnotherProduct;

const productsAsArray: Product[] = [];

the situation here is that sometimes I will go through all the product types(productsAsArray), and I will render it, then user click on some product and I take it as the productSelected. how should I type this productSelected if it can be of any type of product? and for this selectedProduct I will access product-specific properties…

Filter Data to match a list of keys

I have some code that will filter data to match a specified set of keys. So far, my code handles whether the data passed in is an array or an object of a specific kind. For example, a car object or an array of car objects, and the key list would be car attributes. However, I’ve just gotten a new dataset and I’m wondering the best way to go about handling it. Here is my code so far (don’t worry too much about my array/object validation, I have custom functions that do much more checking)

const goodDataObject = {
  "make": "toyota",
  "model": "rav4",
  "color": "white"
  "mileage": "10000",
  "engine": "hybrid"
};

const goodDataArray = [
  {
    "make": "toyota",
    "model": "rav4",
    "color": "white"
    "mileage": "10000",
    "engine": "hybrid"
  },
  {
    "make": "chevrolet",
    "model": "cruze",
    "color": "black"
    "mileage": "20000",
    "engine": "gas"
  }
]

const badDataObject = {
  "dealer": "John Does Cars",
  "factory": "Michigan",
  "cars": [
    {
      "make": "toyota",
      "model": "rav4",
      "color": "white"
      "mileage": "10000",
      "engine": "hybrid"
    },
    {
      "make": "chevrolet",
      "model": "cruze",
      "color": "black"
      "mileage": "20000",
      "engine": "gas"
    }
  ]
}


// -->> results from goodDataObject:
{
  "make": "toyota",
  "model": "rav4"
}


// -->> results from goodDataArray:
[
  {
    "make": "toyota",
    "model": "rav4"
  },
  {
    "make": "chevrolet",
    "model": "cruze"
  }
]


// -->> results I WANT from badDataObject:
{
  "dealer": "John Does Cars",
  "factory": "Michigan",
  "cars": [
    {
      "make": "toyota",
      "model": "rav4"
    },
    {
      "make": "chevrolet",
      "model": "cruze"
    }
  ]
}

Here is my current code called with keys ["make", "model"].

function filterData(data, keys) {
  let filtered = null;
  
  if (typeof data === 'object') {
    for (let x of keys) {
      filtered[x] = data[x]
    }
  } else if (Array.isArray(data)) {
    filtered = [];
    for (let y of data) {
      let filteredObject = {};
      for (let key of keys) {
        filteredObject[key] = y[key];
      }
      filtered.push(filteredObject);
    }
  }
  return filtered;
}

I need to handle the badDataObject, and I’ve been thinking of a recursive option, but that has not been successful so far so I can’t post much there

How To Shuffle Data In a JSON File

I have multiple text files with file names under different names according to what they stand for but lets use the alphabet in to make it easier. I have these Text files:

a.txt
b.txt
c.txt
.....

and I then have JSON file’s that are associated to these files (where “a.txt” has “a.json”) and a number associated to that file within the JSON file.

.....
"file" : "a.txt"
"number : 15
.....

How could I shuffle the the file names, for example changing a.txt to b.txt and b.txt changes to another letter, whilst keeping the data on the JSON files up to date with the changes. I was thinking to make a script in Python, but I think JS would probably be more suited for a website implementation. Thankyou for any help I receive.

Node Module (robotjs) was compiled against a different Node.js version

So I’m trying to build a simple VS Code extension but after I finally found the right modul to use I can’t get it to run corectly.

After pressing F5 to test the extension i just get the message:

Activating extension 'undefined_publisher.vs-code-media-player' failed: The module '\? 
c:UsersmyNameGoogle Drive3_PersoenlichProgrammingVS Code Extensionsvs-code- 
media-playernode_modulesrobotjsbuildReleaserobotjs.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 83. This version of Node.js requires
NODE_MODULE_VERSION 89. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`)..

I tried:

  • npm rebuild
  • uprgading npm
  • downgrading npm
  • installing another module version
  • create a new project
  • updating node

But nothing worked so far.

Thanks in advance for your help.

Change from ScrollView to FlatList in react native

I’m going to make a todolist app.
On the main page, to show the task of todolist,
I used scrollview, but I want to change it to FlatList.

<ScrollView width = {width-20}>
            {Object.values(tasks).map(item => (
               <Task key = {item.id} item={item} deleteTask={_deleteTask} 
               toggleTask={_toggleTask} updateTask={_updateTask}/>
           ))} 
         </ScrollView>