JavaScript and Node.js

I recently created a function in vanilla JS called fetch to retrieve data from an API. Now, I am looking to send this data to my MongoDB database using Node.js. It's a bit chaotic right now as my friend is handling the backend while I focus on the frontend. We are in the process of combining our code and I'm not quite sure what to do with this 'req' argument in the create function. Any help would be greatly appreciated. Thank you.


const Match = require('../db/models/match');

class MatchController {
    async showMatches(req, res) {        
        const matches = await Match.find();
        res.status(200).json(matches); //parsuje dane na JSON 
        console.log('show');
    }

    async create(req, res) { 

        const match = getDataForSheduleCJS(nameLeague).then(resp => {
            const matchObject = new Match({
                leagueName: resp.competition.name,
                date: resp.utcDate.slice(0, 10),
                awayTeam: resp.awayTeam.name,
                homeTeam: resp.homeTeam.name,
                scoreHomeTeam: resp.score.fullTime.homeTeam,
                scoreAwayTeam: resp.score.fullTime.awayTeam,             
            });
            return matchObject;
        });
     

        // const match = new Match({
        //     leagueName: 'Bundes'
        // });

        try {
            console.log(match);
            await match.save();
            //res.status(201).json(match); 
        } catch (e) {
            console.log('error');
            res.status(422).json({
                errors: e.errors
            }); 
        }
    }
}

module.exports = new MatchController();
    const getDataForSheduleCJS = () => {
            fetch(`https://api.football-data.org/v2/competitions/PL/matches`, {
                headers: {
                  'Content-Type': 'application/json',
                  'X-Auth-Token': personalToken
            }}).then(resp => resp.json())
            // .then(data => data)
            .catch((error) => {
                alert("Wystąpił problem z danymi")
                console.error('Error:', error);
            });
        }


const express = require('express');
const router = new express.Router(); //zmieniamy nazwy z app.get na router.get
const MatchController = require('../controllers/match-controller');

router.get('/matches', MatchController.showMatches);
router.post('/matches', MatchController.create);

module.exports = router;

Answer №1

In this API, the 'req' function is utilized to retrieve body data or query parameters from the frontend. For instance, when you send data in a POST request to the backend, the 'req.body' in the backend API will contain the object that was sent from the frontend. For example, if you are trying to create a new user and sending the username and password to the backend API, this 'req' will contain the object:

{
  name:'Some Name',
  password:'somePassword'
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uploading audio mp3 files with Angular 2 and ExpressJS to the server (maximum size of 16MB)

I am embarking on a new project that will require users to upload audio MP3 files under 16MB in size, which falls within the maximum file size limit for mongoDB. I have been researching but haven't found a clear solution on how to handle this on the s ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

Mastering the use of npm and sails to create HTML-PDF files effortlessly

UPDATE: I am simplifying my question and will address any other concerns in separate posts if necessary. The initial post was too lengthy, hoping for a straightforward guide on utilizing sails to its fullest potential. Apologies. To begin with, my knowled ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

Numerous input fields available for AJAX auto-complete functionality and name verification

Currently, I am working on implementing a text box that will search through a mysql database and display auto-completed text below the input field. Additionally, I want to include a visual indicator like a confirmation tick or cross to signify whether the ...

Place the file in the designated area for styling purposes

Within the pluploader, a file drop zone exists with the identifier dropFilesHere; var uploader = new plupload.Uploader({ drop_element : "dropFilesHere", /*...*/ }); If a user hovers a file over the drop zone, I want to customize it* ...

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

Can I programmatically retrieve a comprehensive list of all global HTML attributes available?

Exploring the extensive list of global HTML attributes can be overwhelming, especially when considering how it continues to evolve with browser updates. Can JavaScript be leveraged to dynamically generate a complete list of these attributes without the ne ...

AJAX does not execute all inline JavaScript code

I am currently using AJAX to load a fragment of a document. I have successfully loaded 'external' scripts, but I am encountering issues when trying to execute all the JavaScript within <script> tags. Below is an example of the HTML fragmen ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Leveraging Material-UI in Electron Environment

I'm currently working on an electron app using React and incorporating Material-UI for the user interface. I've added a datepicker and timepicker to a component, but when clicking on the input in the electron app, nothing happens. I'm unsure ...

Tampermonkey's .click() function appears to be malfunctioning

I am attempting to automate clicking a button in Tampermonkey, but for some reason the code is not working as expected. Interestingly, when I manually run the code in the console, it functions perfectly. Here is the snippet: $(document).ready(function() ...

What is causing express.js not to authenticate properly?

I'm currently in the process of developing a server application using node.js, which is up and running on localhost:8080. As I attempt to make a login request, I've encountered an issue where one method works while the other fails. My suspicion i ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

What is the maximum number of tables that can be stored in a

Would having an excessive number of tables in a database be considered detrimental? Currently, I have around 160 tables stored within a single database. Would it potentially improve performance to distribute these tables across multiple databases rather ...

Error encountered when accessing Spotify API. The requested action requires proper permissions which are currently missing. Issue arises when attempting to

I am attempting to use the spotify-web-api-node library to play a track on my application const playSong = async () => { // Verify access token with console.log(spotifyApi.getAccessToken()) setCurrentTrackId(track.track.id); setIsPlay ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

Guide on repeatedly clicking the Cookie to enjoy Cookie Clicker on https://orteil.dashnet.org/cookieclicker/ with the help of Selenium and Python

I've been attempting to create a selenium program for playing Cookie Clicker, but I'm encountering some issues. Here's the code I have so far: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains P ...

Creating dynamic HTML and CSS in ASP.NET: A step-by-step guide

I am currently working on integrating a photo album in my asp.net website. I have been able to successfully display 3 images from a specific album by selecting their URLs from the database. However, I am facing an issue when a user has multiple albums. I n ...

Revolutionize your rotation axis with Axis in three.js

Greetings! I am currently working with three.js and I am attempting to rotate my 3D model along the x-axis. However, when I use the following code: object.rotation.x += 0.01;, it does not produce the desired effect. The image below depicts the current ro ...