why is my vue-router not rendering my files?

I tried to use the Vue-router in my Vue project.
I installed it with npm install vue-router@latest.
My problem right now is, that it isn`t working

My router.js file looks like this:

import Vue from 'vue';
import Router from 'vue-router';
import Home from './src/components/Home.vue'

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home 
    },
  ],
});

then I want to import it into the App.vue file with the <router-view></router-view>tag, but here is the whole file:

<script setup>
import { RouterView } from 'vue-router';
</script>

<template>
    <router-view></router-view>
</template>

Here is also a picture from the file structure:

enter image description here

Home.vue is just the whole landingpage, but when I run the server with npm run dev, it just shows a white page. Does someone know what the problem here is?

URL query does not filter as expected

I have made a small api together with a collection in mongodb which I named just ‘test’. Every document in it has two fields – ‘letter’ and ‘nmbr’, the value of ‘letter’ being either ‘x’ or ‘z’ or ‘y’, and the value of ‘nmbr’ either a positive integer or a negative integer. Then I wrote this piece of code:

app.get('/tests/:par?nmbr[gt]=0', (req, res) => { Test.find({letter: req.params.par, nmbr: {$gt: 0}}) .then(data => res.status(200).json({data})); });

When I sent this GET request in postman – localhost:5000/tests/x?nmbr[gt]=0, I expected to receive as a response only those documents, in which the value of ‘letter’ is ‘x’ and the value of ‘nmbr’ is a positive integer.
Instead, in the response were included not only those documents, in which the value of ‘letter’ is ‘x’, but also the documents in which the value of ‘nmbr’ is a negative number.
So my question is why? Where did I go wrong?

django web app accessed by multiple users

I’m trying to implement a web based quiz application

I’m currently using django and html / JavaScript – only running on localhost so far
(python manage.py runserver)

For one single user, the quiz is working fine, but multiple users are not able to play individually atm.

How do i handle concurrent access to the quiz? I considered using the request.session data structure but storing the complete quiz in there somehow feels wrong. And different users might play a totally different set of questions …

Somehow I’d like to start a new thread each time a user access the webpage and starts the quiz (like I’d do it in some offline application), but im not sure if this is the right approach for web dev.

I also read that this is maybe done by the real webserver, e.g. apache? Should I try to put the django app on apache?

Also considered docker and started a small tutorial this morning.

I can post some code ofc, or provide more implementation details if necessary but at the moment I need to get a basic understanding of web development best practices 😉

Scenario:

User A starts quiz and answers the first 5 questions.

User B starts quiz – it will start at question 6.
–> User B should start at question 1.

How can i isolate User A from User B?

why does any interaction with the django site direct you to the data addition form?

The task was given to develop a service for working with the restaurant database on django. Clicking on the corresponding buttons /fields of the data table should redirect to pages with edit/add/delete forms, but any interaction with the site redirects only to the page for adding new data. I’ve been trying to find the reason for this behavior for several hours, but nothing comes out. Below is the html markup of one of the pages, views, forms and URLs for working with one of the database tables.

<body>
    {% include 'main/navbar.html' %}
    <h1>restaurants</h1>
 
    <div class="add">
        <form method="post" action="{% url 'create_restaurant' %}">
            {% csrf_token %}    
            {{ form.as_p }}
            <button type="submit" class="btn btn-success">Добавить</button>
        </form>
    </div>
 
    <table class="table">
        <ul></ul>
        <thead>
            <tr>
                <th>Address </th>
                <th>Phone number</th>
                <th>Delivery area</th>
                <th>Menu</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            {% for restaurant in restaurants %}
                <tr data-id="{{ restaurant.id }}">
                    <td class="editable-field" data-field="address">{{ restaurant.address }}</td>
                    <td class="editable-field" data-field="phone">{{ restaurant.phone }}</td>
                    <td class="editable-field" data-field="district">{{ restaurant.delivery_code.district }}</td>
                    <td class="editable-field" data-field="menu">{{ restaurant.menu_code.name }}</td>
                    <td>
                        <button class="btn btn-danger" data-toggle="modal" data-target="#confirmDeleteModal{{ restaurant.id }}">
                            delete
                        </button>
        
                       
                        <div class="modal" id="confirmDeleteModal{{ restaurant.id }}" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="confirmDeleteModalLabel">Confirmation of deletion</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        are you shure? "{{ restaurant.address }}"?
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">cancel</button>
                                        <form method="post" action="{% url 'delete_restaurant' restaurant.id %}">
                                            {% csrf_token %}
                                            {{ form.as_p }}
                                            <button type="submit" class="btn btn-danger">delete</button>
                                        </form>
                                        
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
        
        
    </table>
    
   
    
   
    <div class="modal" id="editRestaurantModal">
        <div class="modal-dialog">
            <div class="modal-content">
             
                <div class="modal-header">
                    <h4 class="modal-title">Edit a restaurant</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
    
           
                <div class="modal-body">
                    <form id="editRestaurantForm" method="post" action="{% url 'manage_restaurant' %}">
                        {% csrf_token %}
                        {{ form.as_p }}
                        <input type="hidden" name="restaurant_id" value="{{ current_restaurant.id }}">
                        <input type="submit" value="save">
                    </form>
                </div>
 
            </div>
        </div>
    </div>
    
<script>
    $(document).ready(function () {
       
        $('.editable-field').on('click', function () {
            const restaurantId = $(this).closest('tr').data('id');
            const editFormUrl = `/manage_restaurant/${restaurantId}/`;
            console.log('editFormUrl:', editFormUrl);
 
            $('#editRestaurantForm').attr('action', editFormUrl);
 
            
            $.get(editFormUrl, function (data) {
           
                $('#editRestaurantModal').find('.modal-body').html(data);
            });
 
           
            $('#editRestaurantModal').modal('show');
        });
 
       
        $('#editRestaurantForm').submit(function (e) {
            e.preventDefault();
            const editFormUrl = $(this).attr('action');
            const formData = $(this).serialize();
            console.log('Form submitted!');
            console.log('editFormUrl:', editFormUrl);
            console.log('formData:', formData);
 
            $.ajax({
                type: 'POST',
                url: editFormUrl,
                data: formData,
                success: function () {
                    $('#editRestaurantModal').modal('hide');
                    
                    location.reload();
                }
            });
        });
 
       
 
        
        $('input[name="delete_option"]').on('change', function () {
            const deleteOption = $(this).val();
            const formAction = $(this).closest('form').attr('action');
 
            
            const updatedAction = `${formAction}?delete_option=${deleteOption}`;
            $(this).closest('form').attr('action', updatedAction);
        });
    });
</script>

 
    
    
    
    
    
    </body>

views:

def restaurant_list(request):
    restaurants = Restaraunts.objects.all()
    return render(request, 'main/restaurant_list.html', {'restaurants': restaurants})

def manage_restaurant(request, restaurant_id=None):
    if restaurant_id:
        restaurant = get_object_or_404(Restaraunts, pk=restaurant_id)
        form = RestaurantForm(request.POST or None, instance=restaurant)

        if request.method == 'POST':
            if 'delete' in request.POST:
                restaurant.delete()
                return redirect('restaurant_list')
            elif form.is_valid():
                form.save()
                return redirect('restaurant_list')
    else:
        form = RestaurantForm()

    return render(request, 'main/restaurant_list.html', {'form': form})

def create_restaurant(request):
    if request.method == 'POST':
        form = RestaurantForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('restaurant_list')
    else:
        form = RestaurantForm()

    return render(request, 'main/restaurant_list.html', {'form': form})

def delete_restaurant(request, restaurant_id):
    restaurant = get_object_or_404(Restaraunts, pk=restaurant_id)

    if request.method == 'POST':
        form = DeleteRestaurantForm(request.POST)
        if form.is_valid():
            delete_option = form.cleaned_data['delete_option']

            if delete_option == 'cascade':
                restaurant.delete()
            elif delete_option == 'set_null':
                # Установите поля delivery_code и menu_code на NULL
                restaurant.delivery_code = None
                restaurant.menu_code = None
                restaurant.save()

            return redirect('restaurant_list')
    else:
        form = DeleteRestaurantForm()

    return render(request, 'main/restaurant_list.html', {'form': form, 'restaurant': restaurant})

url-s:

path('', restaurant_list, name='restaurant_list'),
    path('manage/', manage_restaurant, name='manage_restaurant'),
    path('manage_restaurant/<int:restaurant_id>/', manage_restaurant, name='manage_restaurant'),
    path('restaurants/manage/<int:restaurant_id>/', manage_restaurant, name='manage_restaurant'),
    path('restaurants/create/', create_restaurant, name='create_restaurant'),
    path('delete_restaurant/<int:restaurant_id>/', delete_restaurant, name='delete_restaurant'),

forms:

class RestaurantForm(forms.ModelForm):
    class Meta:
        model = Restaraunts
        fields = '__all__' 


class DeleteRestaurantForm(forms.Form):
    DELETE_CHOICES = [
        ('cascade', 'Каскадное удаление'),
        ('set_null', 'Установить ссылки на NULL'),
    ]

    delete_option = forms.ChoiceField(choices=DELETE_CHOICES, widget=forms.RadioSelect)

When you click on any field from the table on the site, a form for editing should open in the modal window, but a form for adding a new field opens. When deleting, a modal window appears to confirm the action, then the same form appears for adding, but it contains radiobuttons to select the type of deletion.

Theme toggler not setting id to dark mode

I have this React app and I’m trying to set it up where if the main div id is set to light, the background is a light color and if set to dark it’s a dark color. The ThemeContext is so it affects the entire web page.

export const ThemeContext = createContext(null);

function App(props) {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
    setTheme((curr) => (curr === "light" ? "dark" : "light"));
  };

  return (
    <div id={theme}> // this needs to change from light to dark when I click on the toggler
      <ThemeContext.Provider value={{ theme, toggleTheme }}>
        <Header theme={theme} toggleTheme={toggleTheme} />
        <ToastContainer />
        <Container className="my-2">
          <Outlet />
        </Container>
        <Footer />
      </ThemeContext.Provider>
    </div>
  );
}

I have the main code passed down to the Header as props so I can have the toggler inside my header.

const Header = (props) => {
  return (
    <header>
      <Navbar bg="dark" variant="dark" expand="lg" collapseOnSelect>
        <Container className="nav_container">
          <LinkContainer to="/">
            <Navbar.Brand>Verdant</Navbar.Brand>
          </LinkContainer>
            <Slider // slider
              onChange={props.toggleTheme}
              checked={props.theme === "dark"}
            />
      </Container>
    </header>
  );
};

The slider itself is a simple input

const Slider = () => {
  return (
    <div>
      <label class={styles.switch}>
        <input type="checkbox" />
        <span class={styles.slider}></span>
      </label>
    </div>
  );
};

The slider works fine. When I click on the slider it goes back and forth like it’s supposed to.

But when I inspect the page and I click on the slider, the id isn’t changing from light to dark like it’s supposed to. It stays on light no matter how many times I click it.

Product detail page html css javascript? [closed]

How can I create a product detail page for a product. Right now I have just one product detail page for a single product. And when I click on a different products, it takes me to that product detail page that I have. Do I have to create different pages for each product and link it with window.location? Thanks!

I have just one product on my product detail page. Need to figure out how to view a different product like the one I have

compiling js is always cached error after installing asyncstorage react native expo

i am kinda new to React Native and i am using expo, I am followint a course and during one lecture the teacher uses the package asyncstorage for cache topics. Everything worked fine the data was cached and I fetched the data without any issues. For some reason I wanted to go back how my app was before installing the package so I just commented out all the code that handles caching. I saved the file and the simulator doesn’t update it’s still fetching the data from the cache, I tried so many things like: resetting the chage, installing node again but nothing seems to work is like that file is protected or cached forever no matter what I do doesn’t reflect the changes in the simulator.
What drives me crazy is that if I add some console.log or new code those changes take effect but the data keeps coming from the cache.

here is the full code:

import { create } from 'apisauce';
import cache from '../utility/cache';
import AsyncStorage from '@react-native-async-storage/async-storage';

    const apiClient = create({
        baseURL: 'http://192.168.0.5:9000/api'
    });

    // const clearData = async () => {
    //     try {
    //         await AsyncStorage.clear();
    //         console.log('Cleared AsyncStorage');
    //     } catch (e) {
    //         console.error('Failed to clear AsyncStorage', e);
    //     }
    // };
    // clearData();
  // Changing the implementation of a method
    // const get = apiClient.get;
    // apiClient.get = async (url, params, axiosConfig) => {
    //     // Before
    //     const response = await get(url, params, axiosConfig);
    //     console.log('response => ', response);
    //     if (response.ok) {
    //         cache.store(url, response.data);
    //         return response;
    //     }

    //     // After
    //     const data = await cache.get(url);
    //     return data ? { ok: true, data } : response;
    // };

export default apiClient;
(all the commented code for the first time worked nicely, but then If I deleted them or just commented them in not working it’s like it is protected)

I do not know why is this happening, I was enjoying learning React Native but these things … are the worst part of the journey.

Here is the versions I am using:

     "dependencies": {
        "@react-native-async-storage/async-storage": "1.17.11",
        "@react-native-community/masked-view": "^0.1.11",
        "@react-native-community/netinfo": "9.3.7",
        "@react-navigation/bottom-tabs": "^5.11.15",
        "@react-navigation/native": "^5.9.8",
        "@react-navigation/stack": "^5.14.9",
        "apisauce": "^1.1.1",
        "expo": "~48.0.18",
    "expo-image-picker": "~14.1.1",
    "expo-location": "~15.1.1",
    "expo-status-bar": "~1.4.4",
    "formik": "^2.1.4",
    "lottie-react-native": "5.1.4",
    "moment": "^2.29.4",
    "react": "18.2.0",
    "react-native": "0.71.8",
    "react-native-gesture-handler": "~2.9.0",
    "react-native-progress": "^4.1.2",
    "react-native-reanimated": "~2.14.4",
    "react-native-safe-area-context": "4.5.0",
    "react-native-screens": "~3.20.0",
    "yup": "^0.28.5"
  },```

Like I said: deleting node again, cleaning the cache with all the commands that are out there for expo cli 

can’t able to generate pdf in lwc using pdflib

here i am trying to create a pdf in salesforce using pdflib but when i click create pdf i got his error

import { LightningElement } from "lwc";
import PDFLib from "@salesforce/resourceUrl/pdflib";
import { loadScript } from "lightning/platformResourceLoader";

export default class CreatePDF extends LightningElement {
    async connectedCallback() {
        await loadScript(this, PDFLib).then(() => {
        console.log('jsPDF script loaded successfully');
    })
    .catch(error => {
        console.error('Error loading jsPDF library:', error);
    });
  }
  async createPdf() {
    console.log('inside generatePDF 19');
    const pdfDoc = await PDFLib.PDFDocument.create();
    console.log('inside pdf');
    const timesRomanFont = await pdfDoc.embedFont(
      PDFLib.StandardFonts.TimesRoman
    );

    const page = pdfDoc.addPage();
    const { width, height } = page.getSize();
    const fontSize = 30;
    page.drawText("Learning with Salesforce Bolt !", {
      x: 50,
      y: height - 4 * fontSize,
      size: fontSize,
      font: timesRomanFont,
      color: PDFLib.rgb(0, 0.53, 0.71)
    });

    const pdfBytes = await pdfDoc.save();
    this.saveByteArray("My PDF", pdfBytes);
  }
  saveByteArray(pdfName, byte) {
    var blob = new Blob([byte], { type: "application/pdf" });
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    var fileName = pdfName;
    link.download = fileName;
    link.click();
  }
}

createPDF.js:50 Uncaught (in promise) TypeError: Cannot read properties of undefined

JS: displaying different timezones in specific format

Okay so I have a feature I’m working on for a new site where I need to display current time for both East Coast and West Coast. It needs to be display in the following way:
NY 11:24:21 PM
CA 08:24:21 PM

Thus far I’ve managed to get the time zones to start displaying but I need to make sure they both are pointing specifically only to EST & PST and that they are displaying inside the proper html blocks. I also need the AM/PM to wrap inside a html block.

Here is my sample code:

function showTime() {
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let formatHours = convertFormat(hours)
    
    hours = checkTime(hours)
    hours = addZero(hours)
    minutes = addZero(minutes)
    seconds = addZero(seconds)
    let format = `NY ${hours}:${minutes}:${seconds} <small class="font-medium">${formatHours}</small>`
    let pstDate = date.toLocaleTimeString("en-US", {timeZone: "America/Los_Angeles"}, {timeStyle: 'short'})

    // Output Times
    $('.time-ny').html(format);
    $('.time-ca').html(pstDate);
}

function convertFormat(time) {
    let formmat = 'PM'
    if (time >= 12) {
        format = 'AM'
    }
    return formmat;
}

function checkTime(time) {
    if (time > 12) {
        time = time - 12;
    }
    if (time === 0) {
        time = 12;
    }
    return time
}

function addZero(time) {
    if (time < 10) {
        time = "0" + time;
    }
    return time
}
showTime()
setInterval(showTime, 1000)
body {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #000000;
    flex-direction: column;
}

.clock {
    font-family: sans-serif;
    font-size: 1rem;
    color: #fff;
}

.font-medium {
    font-weight: 500;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clock time-ny"></div>
<div class="clock time-ca"></div>

Any help from you real JS coders would be super appreciated. I dabble in this stuff but it will never be my bread and butter.

Reducers lifecycle action fulfilled show a error

I’m following a tutorial, and it’s a little bit old, like 2 years! When I initialize the project for the frontend, some npm packages are updated, like react, react-router-dom, redux-toolkit, etc. When I create a goal, an error occurs from goalSlice.js

state.goals.push is not a function

But when I downgrade my package.json file, it works fine. Here, I added both package.json files. When the newly upgraded version of npm packages, Why is createSlice.js not working?

goalSlice.js

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import goalService from './goalService'

const initialState = {
    goals: [],
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: '',
}

// Create new goal
export const createGoal = createAsyncThunk(
    'goals/create',
    async (goalData, thunkAPI) => {
        try {
            const token = thunkAPI.getState().auth.user.token
            return await goalService.createGoal(goalData, token)
        } catch (error) {
            const message =
                (error.response &&
                    error.response.data &&
                    error.response.data.message) ||
                error.message ||
                error.toString()
            return thunkAPI.rejectWithValue(message)
        }
    }
)

// Get user goals
export const getGoals = createAsyncThunk(
    'goals/getAll',
    async (_, thunkAPI) => {
        try {
            const token = thunkAPI.getState().auth.user.token
            return await goalService.getGoals(token)
        } catch (error) {
            const message =
                (error.response &&
                    error.response.data &&
                    error.response.data.message) ||
                error.message ||
                error.toString()
            return thunkAPI.rejectWithValue(message)
        }
    }
)

export const goalSlice = createSlice({
    name: 'goal',
    initialState,
    reducers: {
        reset: (state) => initialState,
    },
    extraReducers: (builder) => {
        builder
            .addCase(createGoal.pending, (state) => {
                state.isLoading = true
            })
            .addCase(createGoal.fulfilled, (state, action) => {
                state.isLoading = false
                state.isSuccess = true
                state.goals.push(action.payload)
            })
            .addCase(createGoal.rejected, (state, action) => {
                state.isLoading = false
                state.isError = true
                state.message = action.payload
            })
            .addCase(getGoals.pending, (state) => {
                state.isLoading = true
            })
            .addCase(getGoals.fulfilled, (state, action) => {
                state.isLoading = false
                state.isSuccess = true
                state.goals = action.payload
            })
            .addCase(getGoals.rejected, (state, action) => {
                state.isLoading = false
                state.isError = true
                state.message = action.payload
            })
    },
})

export const { reset } = goalSlice.actions;
export default goalSlice.reducer

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "proxy": "http://localhost:5050",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.7",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.5.1",
    "axios": "^1.6.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.12.0",
    "react-redux": "^8.1.3",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.1",
    "react-toastify": "^9.1.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Downgraded package.json file

{
  "name": "frontend",
  "version": "0.1.0",
  "proxy": "http://localhost:5000",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.7.2",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.25.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-redux": "^7.2.6",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "react-toastify": "^8.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

PokiAPI JS Function call using AXIOS/EXPRESS to get pokemon name and image

Im attempting to gather the pokemon name and image from the pokeAPI as an index page to display both next to each other. Its my first time using API’s and havnt really gotten into Promisses yet.
My question is as a very new developer working on a passion project how would I gather both the Name and the image in a call. This uses the following API url:
https://pokeapi.co/api/v2/pokemon?limit=100000&offset=0

dont mind the security portion.

router.get('/all', (req, res) => {
    const { username, loggedIn, userId } = req.session
    // we have to make our api call
    axios(allPokemonUrl)
        // if we get data, render an index page
        .then(apiRes => {
            console.log('this came back from the api: n', apiRes.data.results)
            res.render('pokemon/index', { pokemon: apiRes.data.results, username, userId, loggedIn})
    })
    // if something goes wrong, display an error page
    .catch(err => {
        console.log('error')
        res.redirect(`/error?error=${err}`)
    })
})

Ive tried several things. Attempting to grab the poke number and then using the number as a reference in the github images for the “image” since its a contstant but I couldnt get it to work. As I as I said im very new. 🙁

best way to dissect html from a request in nodejs

I am getting html page of a website by using request of nodejs. Sample code is as :

const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

I want to get the elements of the body by using tags like I would do on a browser console

like body.getElementById("myId"); or document.getElementById() sort.

Maybe there are multiple ways of doing this with different libraries(node modules), but what is the most efficient way to do this? I will be fetching many pages and I want to get elements by tags possibly using javascript please help me on how to do this.

Why do I get ‘ReferenceError: expression is not defined’? I use pegjs

Here is my language code.
I am a native Hispanic, so the labels and some parts are in Spanish, but the rest of the code, according to me, is in English.

What I want to do is create a function-oriented programming language in pegjs.

The language aims to create video game engines; graphics engines; web pages and video games.

I am creating the language as a personal challenge and also to have something to do

The error “ReferenceError: expression is not defined” indicates that you are trying to use the variable expression in a place where it is not defined or has not been previously declared in the code although, I have already tried to put it after having declared expression but it still does not work.

Help me please.

start 
= variableLoc / variableVarion / variableConst / variableEntro / variableDal / variableTex / declaracionFunciones / llamarFuncion / login /ingre / ingreNum /ingretro / ingreDal

  //funciones
  declaracionFunciones =
  "func" space id:id "(" parameterList:parameterList? ")" "{" statement:statement* "}" {
    return { type: "declaracionFunciones", id, parameterList:parameterList || [], statement };
  }

  llamarFuncion =
  id:id "(" parameterList:parameterList? ")" ";" {
    return { type: "llamarFuncion", id, parameterList: parameterList || [] };
  }

   login
  = "login" space "(" target:id "," value:expression "," optionalTarget:id? ")" ";" {
    return { type: "login", target, value, optionalTarget: optionalTarget || null };
  }

  ingre = "ingre" space? "(" target:id ")" ";" {
  variable[target] = prompt(target);
  return { type: "ingre", target, value: variable[target] };
  }

  ingreNum = "ingreNum" space? "(" target:id ")" ";" {
  
  Number.isFloat = Number.isFloat || function(value) {
  return typeof value === 'number' && 
    isFinite(value) &&
    Math.floor(value) !== value;
};
  let inputValue = prompt(target);
  let num = prompt(target);
  let parsedValue = Number(inputValue);
  
  if (Number.isInteger(parsedValue)) {
    variable[target] = parseInt(num);
  } else if (Number.isFloat(parsedValue)) {
    variable[target] = parseFloat(num);
  } else {
    try {
      throw new Error("Sintax error");
    } catch(error) {
      console.error(error.message);
    }
  }
  
  return { type: "ingreNum", target, value: variable[target] };
};

  ingretro = "ingretro" space? "("target:id")" ";" {
    variable[target] = parseInt(prompt(target));
    return { type: "ingretro", target, value: variable[target] };
  };

  ingreDal = "ingreDal" space? "("target:id")" ";" {
    
  Number.isFloat = Number.isFloat || function(value) {
  return typeof value === 'number' && 
    isFinite(value) &&
    Math.floor(value) !== value;
};
    variable[target] = parseFloat(prompt(target));
    return { type: "ingretro", target, value: variable[target] };
  };

  //Declaración de variables
  variableLoc =
  "loc" space id:id (space? "=" space? expression:expression)? ";" {
    return { type: "variableLoc", id, expression:expression, isLocal: true };
  }

  variableVarion =
  "varion" space id:id (space? "=" space? expression: expression)? ";" {
    return { type: "variableVarion", id, expression, isGlobal: true };
  }

  variableConst = 
  "const" space id:id (space? "=" space? expression)? ";" {
    return { type: "variableConst", id, expression, isConstant: true, isLocal: true };
  }

  variableTex =
  "tex" space id:id (space? "=" space? string:string)? ";" {
    return { type: "variableTex", id, string:string, isLocal: true};
  }

  variableEntro =
  "entro" space id:id (space? "=" space? numberEntro:numberEntro)? ";" {
    return { type: "variableEntro", id, numberEntro:numberEntro, isLocal: true };
  }

  variableDal =
  "dal" space id:id (space? "=" space? numberDal:numberDal)? ";" {
    return { type:"variableDal", id, numberDal:numberDal, isLocal: true };
  }

  //Reglas de declaración de variable
  id = [a-zA-Z_][a-zA-Z0-9_]* {
  return text();
  }

  expression = number / string / boolean / id

  //Numeros
  number = integer / float / negativeInteger / negativeFloat / specialValue

  numberEntro = integer / negativeInteger

  numberDal = float / negativeFloat

  integer = [0-9]+ {
  return parseInt(text(), 10);
  }

  float = [0-9]+ "." [0-9]+ {
  return parseFloat(text(), 10);
  }

  negativeInteger = "-" integer {
  return -parseInt(text(), 10);
  }

  negativeFloat = "-" float {
  return -parseFloat(text(), 10);
  }

  specialValue = "NaN" {
    return { type: "specialValue", value: NaN };
  }
  / "INF" {
    return { type: "specialValue", value: Infinity };
  }
  / "-INF" {
    return { type: "specialValue", value: -Infinity };
  }

  //Strings
  string = stringDouble / stringSingle / stringTemplate / stringTemplateContent

  stringDouble = '"' chars:stringContent* '"' {
  return chars.join('');
  }

  stringSingle = "'" chars:(stringContent / "\'")* "'" {
  return chars.join('');
  }

  stringTemplate = "`" chars:stringTemplateContent* "`" {
  return chars.join('');
  }

  stringTemplateContent = "${" expression:expression "}" {
    return "${" + expression + "}";
  }
  / [^$]+


  stringContent = [^"] / "\" . ;

  //Booleanos
  boolean = "true" / "false" {
    return text() === "true";
  }

  //Reglas de funciones
  parameterList
  = parameter (space "," space parameter)*

  parameter
  = expression:expression space id:id {
    return { type: "parameter", expression:expression, name: id };
  }

  outputStatement
  = "consola" ":" expression:expression ";" {
    return { type: "outputStatement", target: "consola", value: expression };
  }
  / "documento" ":" expression:expression ";" {
    return { type: "outputStatement", target: "documento", value: expression };
  }

  statement
  = outputStatement/ login / expression / assignment / returnStatement

  assignment
  = id:id space "=" space expression:expression ";" {
  return { type: "assignment", variable: id, value: expression };
  }

  returnStatement
  = "regresa" space expression:expression ";" {
  return { type: "returnStatement", value: expression };
  }

  //Reglas generales
  space = " "*

  variable = statement:statement {
  return { variables: {}, statement };
  }

I was hoping to be able to do:

varion a;

a = 10;

login("consola",a);

ReferenceError: expression is not defined