Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed from the front end. The first call is a preflight with an options method, followed by another pending request without a specified method. I have attached screenshots for reference: API Call

Below is the code snippet for the problematic API:

router.put("/carrousel-item/update/:id", fileUpload, (req, res) => {
    req.getConnection((err, conn) => {
        try {
            const image = fs.readFileSync(
                path.join(__dirname, "../images/" + req.file.filename)
            );
            const title_en = req.body.title_en;
            const title_es = req.body.title_es;
            const sub_title_color_1_en = req.body.sub_title_color_1_en;
            const sub_title_color_1_es = req.body.sub_title_color_1_es;
            const sub_title_color_2_en = req.body.sub_title_color_2_en;
            const sub_title_color_2_es = req.body.sub_title_color_2_es;
            try {
                conn.query(
                    `UPDATE home_team_section SET ? WHERE id = ?`,
                    [
                        {
                            title_en: title_en,
                            title_es: title_es,
                            sub_title_color_1_en: sub_title_color_1_en,
                            sub_title_color_1_es: sub_title_color_1_es,
                            sub_title_color_2_en: sub_title_color_2_en,
                            sub_title_color_2_es: sub_title_color_2_es,
                            image: image,
                        },
                    ],
                    (err, rows) => {
                        res.send(rows);
                    }
                );
            } catch (error) {
                console.log(error);
            }
        } catch (error) {}
    });
});

This issue has become a roadblock in my project progression as it prevents me from executing any new APIs successfully.

Note: I have already included the cors() middleware in my setup.

I would greatly appreciate any assistance you can provide in resolving this matter.

Answer №1

const LabelModel = require("../models/labelModel")
const express=require('express')
const router=express.Router()

class LabelController{
    static displayLabels(request,response){
        LabelModel.fetchLabels((error,data)=>{
            if (error) {
                response.send(error)
            }else{
                // console.log(data);
                response.render('labelView',{ newResult:data })
            }
        })
    }

Answer №2

   function retrieveSongsData(callback){
        let query=`
        SELECT l."name",l.id FROM "Labels" l;`
        pool.query(query,(err, res)=>{
            if (err) {
                callback(err)
            }else{
                let newData=res.rows
                callback(null,newData)
            }
        })}

    function addNewSongData(request,callback){
        
        const title=request.body.title
        const bandName=request.body.bandName
        const duration=request.body.duration
        const genre=request.body.genre
        const lyric=request.body.lyric
        const imageUrl=request.body.imageUrl
        const label=request.body.label
        const createdAt=request.body.createdAt

        let errorMessages=[]
        if (!title) {
            errorMessages.push("Title is required")
        }
        if (title.length>=100) {
            errorMessages.push("Title should not exceed 100 characters")
        }
        if (!bandName) {
            errorMessages.push("Band name is required")
        }
        if (!duration) {
            errorMessages.push("Duration is required")
        }
        if (duration<60) {
            errorMessages.push("Minimum duration should be 60 seconds")
        }
        if (!genre) {
            errorMessages.push("Genre is required")
        }
        if (!lyric) {
            errorMessages.push("Lyric is required")
        }
        if (lyric) {
            let countSpaces=0
            for (let i = 0; i < lyric.length; i++) {
                if (lyric[i]===" ") {
                    countSpaces++
                }
            }
            // console.log(countSpaces);
            if (countSpaces<10) {
                errorMessages.push("Minimum of 10 words required in lyric")
            }
        }
        if (!imageUrl) {
            errorMessages.push("Image URL is required")
        }
        if (imageUrl<=50) {
            errorMessages.push("Maximum length of Image URL is 50 characters")
        }
        if (!label) {
            errorMessages.push("Label Company is required")
        }
        if (!createdAt) {
            errorMessages.push("Date is required")
        }
        if (createdAt) {
            let currentDate = new Date().toJSON().slice(0, 10);
            if (createdAt>currentDate) {
                errorMessages.push("Maximum created date should be today")
            }
        }
        // console.log(errorMessages);
        
        if (errorMessages.length!==0) {
            // console.log(errorMessages);

            callback(errorMessages)
        }else{
            let voteCount;
            const {title,bandName,duration,genre,lyric,imageUrl,label,createdAt}=request.body
            const dataValues=[title,bandName,duration,genre,createdAt,lyric,imageUrl,voteCount=0,label]
            let query=`
            INSERT INTO "Songs" ("title","bandName","duration","genre","createdDate",lyric,"imageUrl","totalVote","LabelId") 
            VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9);`
            pool.query(query,dataValues,(err,res)=>{
                if (err) {
                    callback(err)
                    console.log('ERROR IN QUERY');
                }else{
                    console.log("Data added successfully");
                    callback(null,1)
                }
            })
        }

        
    }

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

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...

Best practices for handling errors beyond network problems when using the fetch() function

I am facing a situation where the route of my fetch() call can result in two different responses, each requiring a different action. However, I have noticed that the catch() method only handles network errors as far as I know. Currently, my code looks lik ...

The AngularJS directive seems to be having trouble receiving the data being passed through its scope

Check out this HTML code snippet I created: <div ng-controller="ctrl"> <custom-tag title = "name" body = "content"> </custom-tag> </div> Take a look at the controller and directive implementation below: var mod = angular.mod ...

Seeking assistance with transferring jQuery to regular JavaScript and installing on the home screen of an Apple device

Dealing with the issue of iPhone "Bookmark to Homescreen" removing cookies and sessions, I have come up with a jQuery solution. Learn more about this problem here. In essence, by using JavaScript to create add to homescreen kit launch links, you can avoi ...

Despite a successful request, the React Redux action was not dispatched

I'm currently working on adding authentication to my project. While the user registration part seems to be working, the actions are not being dispatched. Strangely, a similar action for fetching data is working fine and dispatching the actions. Here&a ...

Switching minimum and maximum input values based on a specific condition: A step-by-step guide

I am looking for a way to reverse the minimum and maximum values of two input elements that I have defined. Is there a way to achieve this using HTML or JavaScript (Angular)? Here is an example of what I am trying to do: <label> Width: < ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

What are the best practices for managing user forms and uploading files?

How should data in text fields and file upload fields be handled according to best practices? This question is a more generalized version of one I previously asked, which can be found here. Let's consider the scenario of a user registering an accoun ...

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

Can we maintain an active connection by flushing a node's response to the client?

I am facing a challenge with a large data-set that needs to be converted to CSV for a client. The processing of the entire set at once causes it to time out before completion. To address this issue, I have started loading the data in chunks for more effici ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Caution in React: Utilizing functions with Object.assign() may not be a valid approach when dealing with React children

I have a setup using react for front-end and node for back-end. My goal is to retrieve data from the server to update the user entries on the front-end. I came across using Object.assign() as a potential solution to re-render user entries, but encountered ...

Ways to conceal ng repeat using ng if

My autocomplete feature is set up using ng-repeat to display suggestions and ng-click to change the textbox value. However, I am facing an issue where the suggestion does not disappear when the textbox value is already the same as the suggestion. How can I ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Selecting radio buttons across multiple div classes

I've been struggling to programmatically select specific radio buttons on a webpage. My goal is to automatically choose the second option in each group of radio buttons, but I'm getting lost in the syntax. Unlike most examples I've found on ...

Is it really necessary to import React from 'react' in the index.js file when importing react is no longer required?

Currently diving into the world of React.js. I recently found out that after version 17, importing React is no longer necessary. My current React version is v18.2.0. Here's the code snippet in question: // import React from 'react'; import ...

Using the OR operator in an Angular filter

How can I create a filter with a range slider that shows multiple categories when it's in a certain position? I have tried using the code below to filter based on the range, but it only captures the first word after the OR operator. Can anyone provid ...

Utilizing Angular JS to ensure services are universally accessible across controllers and views

Imagine we have a service like this: myApp.factory('FooService', function () { ... Now, from a controller, the code would look something like this: myApp.controller('FooCtrl', ['$scope', 'FooService', function ($s ...

A Guide on Renaming Files Downloaded Using the http.get() Method in Node.js

I am currently retrieving a file from AWS S3, however, I would like to rename the downloaded file to newName.txt app.get('/', function(req, res){ let URL = "http://bucket-name.s3.amazonaws.com/uploadedFile.txt" http.get(URL,func ...