Managing SQLite errors when using JavaScript and ExpressJS

I have developed a Backend route to retrieve games based on specific letters provided. Below are the two routes that I implemented:

router.get("/public/gamelist/:letter", (req, res, next) => {
  var sql = "SELECT title FROM Games WHERE title LIKE ? || '%' AND ownage = 'true'"
  var params = [req.params.letter]
  db.all(sql, params, (err, rows) => {
    if (rows) {
      return res.status(200).json(rows);
    } else if (!rows) {
      return res.json({ "answer": "NoGame" })
    } else if (err) {
      res.status(400).json({ "error": err.message });
      return;
    }
  });
});

router.get("/public/game/:title", (req, res, next) => {
  var sql = "select * from Games where title = ?"
  var params = [req.params.title]
  db.get(sql, params, (err, row) => {
    if (row) {
      res.status(200).json(row);
    } else if (!row) {
      console.log("Dont exist")
      return res.json({ "answer": "NoGame" })
    } else if (err) {
      res.status(400).json({ "error": err.message });
      return;
    }
  });
}); 

The second route /public/game/:title is functioning correctly, however, the first one /public/gamelist/:letter is not handling empty results properly. It consistently returns a 200 status code even when no game matches the query, returning an empty array instead of

({ "answer": "NoGame" })

Can anyone identify what might be incorrect in this portion of my code?

Answer №1

// Let's code together
const app=require('express')
const paths = require('./paths')
const server=app()

server.set("view engine","ejs")
server.use(app.urlencoded({ extended: true }))

server.use("/", paths)

server.listen(3000,()=>{
    console.log("SERVER UP AND RUNNING");
})


Answer №2

    function handleAddSongRequest(request,response){
        let errorMessage=request.query.errorMessage
        if (!errorMessage) {
            errorMessage=[]
        }else{
            errorMessage=errorMessage.split(',')
        }
        console.log(errorMessage);
        ModelSongs.addNewSong((err,data)=>{
            if (err) {
                response.send(err)
            }else{
                // console.log(errorMessage);
                response.render("addSongForm",{data,errorMessage})
            }
        })
    }
    function handleAddSongSubmission(request,response){
        // console.log('This is from the controller');
        ModelSongs.submitNewSong(request,(err,data)=>{
            if (err) {
                // console.log(err);
                response.redirect(`/songs/add?errorMessage=${err}`)
            }else{
                response.redirect('/songs')
            }
        })
    }

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 it possible to utilize a JavaScript variable as a node in a JSON stringification request?

After successfully retrieving data from the Bungie API previously, I am now facing a challenge in reading a specific JSON file. http://prntscr.com/k3tin3 I'm currently stuck on how to extract a node from the JSON and then utilize it to request charac ...

Swapping out a subarray within an array containing objects with a fresh array consisting of objects

Here is the structure of my data document: { "_id": "6287a6c5975a25cc25e095b0", "userName": "Robot", "projectName": "TestProject", "projectTypeName": "fixed project", "pro ...

Tips for minimizing padding in X-Range graphs

Is there a way to reduce the overall height of my X-Range chart by adjusting the padding on the Y axis around each series? I have experimented with different properties, such as adding groupPadding: 0, pointPadding: 0, and other parameters using this jsfi ...

Error encountered in Google's Structured Data Testing Tool

<script type="application/ld+json"> {"@context" : "http://schema.org", "@type" : "LocalBusiness", "name" : "mywebsite.com", "description": "Lorem ipsum dolor sit amet", "image" : "http://mywebsite.com/image.jpg", "telephone" : "987654321", ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

Challenges with personalized music player

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style type="text/CSS"> #custom{ font-family: monospace; font-size: 16px; max-width: 650px; ...

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...

How to import a module from the root path using TypeScript in IntelliJ IDEA

Despite this topic being widely discussed, I still struggle to understand it. Below is my tsconfig.json file: { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceMap": true, "declaration": true, "allowSyntheticDe ...

Consistently encountering errors when trying to install npm

While attempting to install the Search git whodotheyserve. com application, I encountered a persistent error that shows up regardless of what troubleshooting steps I take. I have experimented with different versions of npm, all of which are successfully in ...

How to utilize a Jquery loop, implement a condition, and store the results in

After using dd() in PHP, the array displayed is as follows: 1 [▼0 => "1,18,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,19,20,21,22,23,24"] I need to iterate through the array and o ...

AngularJS using the ng-controller directive

I am presenting the following HTML code excerpt... <!DOCTYPE html> <html lang="en-US" ng-app> <head> <title>priklad00007</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angula ...

Facing an ERR_SSL_PROTOCOL_ERROR while working with Heroku, Node.js, Express, and SSL encryption

Lately, I activated SSL for my website hosted on Heroku, wildcodemonkey.com, but Chrome shows me the error "ERR_SSL_PROTOCOL_ERROR" whenever I try to access it. From what I've gathered, the SSL connection ends at Heroku's router, which then forw ...

Assign the "this" keyword of App.vue to the Vuex state

I have discovered a workaround for accessing vue-router and other services that only works within a Vue component. By saving the "this" of the Vue app in the state of Vuex within the created option of App.vue. Is this a good approach or could it potential ...

Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date. getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) { var date = new Date(millisSinceEpoch); if (d ...

JavaScript Event Listener not Working Properly

I've been attempting to implement a feature on my website where the header hides when scrolling down and re-appears when scrolling up. However, I'm struggling to make use of the code snippet below to achieve this functionality. Despite my thoroug ...

Inform parent component about changes in child input using Angular

In my current setup, I have a parent component that holds a data object. This data object is passed down to two child components, all of which have an onpush strategy. Each child component contains a form that updates specific properties in the data object ...

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

Prevent a form from loading depending on the response received from an ajax callback

I am currently working on implementing an ajax post function. The process involves sending data and receiving a callback from PHP with some data in return. Depending on the returned data, I need to make a decision whether to proceed or allow the user to re ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...