Implementing the passing of arrays into SQL queries using Express, MSSQL, and React

I'm trying to insert two arrays into my SQL database. Here is a snippet from my server.js file that utilizes an endpoint on the client side:

Express setup:

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");
  try {
    await sql.connect(config);

    // create Request object
    var request = new sql.Request();

    let results = req.body.results;

    let questions = [];
    let answers = [];

    results.forEach(element => questions.push(element.question));
    results.forEach(element => answers.push(element.answer));

    for (var i = -1; i < results.length; i++) {
      request.input("Question", sql.VarChar, questions[i]);
      request.input("Answer", sql.VarChar, answers[i]);
      request.execute("dbo.AddQuestionResponses", function(err, recordset) {
        if (err) console.log(err);
        // send records as a response
        res.json(recordset);
      });
    }
  } catch (e) {
    console.log(e);
  }
});

My SQL stored procedure:

alter procedure AddQuestionResponses
@Question nvarchar (50),
@Answer nvarchar (50)


as 

insert into QuestionResponses(QuestionWhenAnswered, QuestionResponse)
values (@Question ,@Answer )




However, I encounter this error:

RequestError: The parameter name Question has already been declared. Parameter names must be unique

I suspect this issue arises from:

  request.input("Question", sql.VarChar, questions[i]);
      request.input("Answer", sql.VarChar, answers[i]);

Since they are inside a loop, they are repeated causing the conflict. Is there a way to ensure uniqueness and make a successful transaction with the database?

Thank you for your time :)

Answer №1

The problem was successfully resolved when I included

var request = new sql.Request();

inside the for loop.

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

"Combining jQuery and JavaScript to handle form submissions in un

What happens when you combine the Javascript onSubmit handler and jQuery submit handler? <form action="" method="post" onSubmit="myJavascriptHandler();"> <input type="submit" /> </form> <script type="text/javascript"> $("form") ...

Angular/JS - setTimeout function is triggered only upon the occurrence of a mouse click

I'm currently working on a website that calculates the shortest path between two points in a grid utilizing AngularJS. Although I have already implemented the algorithm and can display the colored path, I am facing an issue where the color changes ti ...

Is there a need to minify if the data will be compressed through gzip during

During the early days (yes, I'm really showing my age here), it was possible to reference scripts from a renamed zip file using this format: <script archive="path/to.jar" src="some.js"></script> This method was supported in IE4, NS4, and ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...

The issue of Bootstrap dynamic tabs retaining their active state even after switching tabs, leading to elements being stacked

For my university project, I am developing a website that resembles a text editor using Bootstrap as the framework. To create the website menus, dynamic tabs have been utilized. The following is the code snippet I have implemented: <!--Bootstrap ...

The rate of NodeJS requests per second dropped significantly by a factor of four when using NGINX and receiving a 5xx status

Hardware Specifications: Operating System: Ubuntu 20.04 Virtualization Software: VMware Workstation Pro CPU: 4 cores RAM: 6GB Problem Description: After configuring Nginx for my NodeJS server running on localhost, the request rate dropped from approx ...

Issue with calling on-click function from a directive's template not being triggered

I am new to Angular and I'm experiencing an issue with my ng-click not working in certain contexts. Let me share my code and explain the problem more clearly. HTML : <div ng-app='myApp'> <section id="map-orders" ng-controller= ...

Update a specific section of the web panel within Genexus at regular intervals, such as every 10 seconds

I am working on a simple web panel with a notifications icon. I need the icon to refresh every x seconds to check for any unread notifications in the database. I have tried using web notifications in Genexus, but without success. Can anyone suggest how to ...

The keyboard automatically disappeared upon clicking the select2 input

Whenever I select the select2 input, the keyboard automatically closes $('select').on('select2:open', function(e) { $('.select2-search input').prop('focus',false); }); Feel free to watch this video for more i ...

Identifying Dragged Items and Drop Locations in AngularJS Drag and Drop Feature

We are in the process of developing our initial AngularJS application. One element of the website involves allowing users to drag individuals into specific groups. Similar to Google+ circles, a user can select another user and move them into a circle to in ...

app.js is not properly identifying the navigator's language

This is the code snippet for my controller app.controller('languagesCtrl', function($scope) { var lang = window.navigator.language || window.navigator.userLanguage; if (lang === 'it' || 'it-it' || 'it-IT') { ...

jQuery: Gallerific Partially Functioning

Currently, I am attempting to implement the jQuery gallerific plugin on my website located at . The gallery loads correctly, however, both the thumbnail grid and navigation buttons for next/previous images are not functioning as expected. Despite no visi ...

What could be causing the "Invalid utilization of Nulls" issue in my query?

In my work with Excel, I utilize a userform to facilitate internal queries across spreadsheets. Recently, I've encountered the error message "Invalid Use of Null." While I am familiar with the nz null syntax used in SQL MS Access (SQL MS Access - Inva ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

Image loading has been denied

An attempt to load the image 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QA8gBBAEG7NC6zAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH4wwNFQsGe+TrNQAAADxpVFh0Q29tbWVudAAAAAAAUHJvY2Vzc2VkIEJ5IGVCYXkgd2l0aCBJbWFnZU1hZ2ljaywgejE ...

What is the best way to dynamically generate a component and provide props to it programmatically?

I am interested in creating a function that can return a component with specific props assigned to it. Something like a reusable component for Text/View/Pressable, where styles can be extracted and passed as props. Personally, I find it more efficient to s ...

Maintaining a reliable and efficient way to update the userlist in a chatroom using PHP, AJAX, and SQL

I've successfully created a chatroom using PHP, JavaScript, AJAX, and SQL without the use of JQuery or any other tools. I maintain user persistence through session variables to keep users visible on the front page of my website (www.chatbae.com). How ...

The Ion slider's onFinish event is triggered when the page loads, independent of any user interaction with the slider

I am facing an issue with ionslider. I have observed that the plugin triggers the onFinish action without any user interaction when the page is loaded. However, on the demo site ionden.com/a/plugins/ion.rangeSlider/demo_interactions.html, the plugin only r ...

Obtaining an identification using JQuery for content that is constantly changing

I am currently developing dynamic content tabs using PHP, with one of the objects being a datatable within the tab. In order to define the ID via PHP, I use the following code: PHP: echo '<table class="table table-striped table-bordered table-hov ...

Steps for checking if the specified row has been accurately filled out in a loop

Here is an example of how my JSON data is structured: { "main_object": { "id": "5", "getExerciseTitle": "TestFor", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFor", "language": "nl_NL", "exercises": [ { ...