Unable to retrieve all SQLite elements that match a parameter using the Express API, the result returned is undefined

Having an issue with one of my APIs. Everything seems to be working fine, except when I try to fetch all records based on a parameter, I receive an undefined response. What's frustrating is that if I manually enter the search string into my browser, I get the expected response.

Snippet from API:

tilesRouter.param('cardId', (req, res, next, cardId) => {
  console.log('cardId: ', cardId);
  const sql = 'SELECT * FROM tile WHERE card_id = $cardId';
  const values = {$cardId: cardId};
  console.log('param sql: ', sql);
  console.log('param values: ', values);
  db.all(sql, values, (error, tile) => {
    if (error) {
      next(error);
    } else if (tile) {
      console.log('param req:tile: ', req.tile);
      req.tile = tile;
      next();
    } else {
      res.sendStatus(404);
    }
  });
});

tilesRouter.get('/:cardId', (req, res, next) => {
  res.status(200).json({tile: req.tile});
});

Util snippet for Bingo:

Bingo.getTiles = card_id => {
  const url = `${baseUrl}/tiles/${card_id}`;

  return fetch(url).then(response => {

    if (!response.ok) {
      return new Promise(resolve => resolve([]));
    }

    return response.json().then(jsonResponse => {
      console.log('jsonResponse: ', jsonResponse); // empty
      return jsonResponse.tiles.map(tile => camelcaseKeys(tile));
    });
  });
};

Screenshot URL:

https://i.sstatic.net/kNOnt.png

Answer №1

It appears that there is an issue with the string literal template in your code. It seems like you are trying to search for a tile based on the cardId value.

tilesRouter.param('cardId', (req, res, next, cardId) => {
  console.log('cardId: ', cardId);
  const sql = 'SELECT * FROM tile WHERE card_id = $cardId';

In order to inject the cardId variable properly, you should use template literals:

const sql = `SELECT * FROM tile WHERE card_id = ${cardId}`;

Here are some key differences to note:

  • Template strings are enclosed by backticks (`) instead of double or single quotes.
  • Template strings can contain placeholders indicated by the dollar sign ($) and curly braces {}.

For more information, you can visit this link.

Answer №2

The problem seems to lie in how the parameter is being passed. When I manually set the SQL statement to

'SELECT * FROM tile WHERE card_id = 26'
rather than using
'SELECT * FROM tile WHERE card_id = $cardId'
, everything functions correctly. Now that I understand that both the SQL statement and API are functioning properly, I will investigate why the parameter value isn't working as intended.

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

Trouble in Jest: Async test error

I encountered a specific error message that reads: Cannot read property 'indexOf' of undefined at Function.isPendingSpecException After some investigation, I pinpointed the problem to this particular line of code: TokenRepositor ...

Attempting to include a standard VAT rate of 5% on the invoice

/* The code format is correct and I don't see any issues on my end, I hope it works well for you. */ I need assistance in adding a fixed VAT (tax) rate of 5%. The tax amount should be displayed on the row, while the total tax should reflect the sum o ...

When attempting to call a function after an unsuccessful AJAX load, the Jquery

Our catalog results page includes an external JavaScript file that utilizes AJAX - I have a jQuery function designed to change the color of a span when it detects specific text. You can view the code below: function ReInitStockColor(){ $(function() { ...

What could be causing my scene to fail to render?

I'm attempting to adapt this particular example into CoffeeScript. Below is a snippet of my code: class Example width: 640 height: 480 constructor: -> @camera = new THREE.PerspectiveCamera 45, @width/@height, 10000 @cam ...

I'm experiencing an issue with Gravity Forms validating hidden fields, is there a solution for this problem?

On my webpage, there are four fields labeled A, B, C, and D. Each field has its own set of conditional logic that determines whether it should be visible or hidden. Let's say a user lands on this page and only field B is displayed while the others are ...

Angular Pagination: An issue arises when deleting records from the first page, as the following page's records are not automatically refilling the first page

I have implemented angular pagination to display records. Each record has a button labeled 'Assign to me'. Clicking on this button removes the selected record from the list. However, I am facing an issue where I display 10 records per page and if ...

Incorporating user input into a form using NodeJS and Angular

I am currently facing an issue while trying to add a new entry using NodeJS with an Angular form. Every time I click on create, the data is not being inputted into the database. To address this, I included the angular.toJson function to convert the input i ...

The specific page redirect to its corresponding mobile page is not functioning properly

Having some issues with the code below that is causing problems when trying to redirect users to specific mobile pages based on the desktop page. Any assistance would be greatly appreciated. function mon() { if ($('body').is('.mon') ...

Error in JavaScript goes undetected when utilizing asynchronous AJAX

Having recently started working with ajax and javascript, I find myself puzzled by the fact that my error is not getting caught when making an asynchronous ajax call. I did some research on a similar issue in this query (Catch statement does not catch thr ...

The structural design of a PHP application using Javascript and CSS in an MVC framework

My team and I are about to revamp the frontend of a large CakePHP 2 application. Our main aim, apart from giving it a fresh look, is to create more reusable SCSS/Javascript code, establish a logical structure in our frontend code as well as the third-party ...

How can I extract a substring from a URL and then save it to the clipboard?

Hi there! I'm working on a project for my school and could really use your expertise. I need help extracting a substring from a URL, like this one: URL = https://www.example.com/blah/blah&code=12432 The substring is: 12432 I also want to display ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

toggle the visibility of a div using an unordered list

One of my challenges involves toggling the visibility of a div (filter-panel--content) containing an unordered list when clicking on the label above it. #LABEL/DIV THAT CAN BE CLICKED AND TRIGGERS .click() <div class="filter-panel--flyout"> <d ...

Refreshing Firebase tokens

Currently, I am utilizing Firebase for authentication within my React application. Additionally, I have an Express server that provides a REST API. This API includes a middleware function that utilizes firebase-admin to verify the idToken sent from my app ...

VueJS / v-html is displaying a blank page (Bokeh-html)

Especially as a newcomer to VueJS, I am currently in the process of trying to showcase a local HTML file within the Vue Application. The method I'm using to fetch the HTML file involves Axios, here's how it goes: <template> <div> ...

delivering JSON data statically with a question mark in the file name using ExpressJS

I am currently experimenting with serving json data statically from the filesystem to create a mock API. Previously, I relied on deployd in my stack and was able to serve /users/names?id=123 from ./users/names?id=123/index.html. However, I decided to remo ...

Reordering a pair of items within an array using ReactJS

After pondering, I wondered if there exists a neat and tidy method to swap two objects within an array while utilizing setState. Here's my current approach: export function moveStepUp(index) { if(index > 0){ let currentStep = this.stat ...

Looping through data and converting it into a JSON format can

Can anyone help me figure out how to work through this JSON data using VUE? I'm having trouble accessing keys that v-for can't seem to reach: [ { "Lavandería": { "id": 1, "name": "Lavandería", "i ...

Certain conditions in JavaScript are not executed by Internet Explorer

I am currently working on a Html file that involves XSLT. I have integrated some JavaScript code for filtering specific rows within tables. However, I have encountered an issue where certain if-cases in my JavaScript are not executing as expected when usin ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...