Express API get one piece of data

Hey, I need help with a question that has been bothering me for a few weeks.

I know how to get all data from a database with get(’/api’, (req, res, next). But how do I get ONE specific piece of data by using a users input from an input form?

For example, I have an sqlite3 table listing animals, their weight, breed, color, etc.

How do I get one specific animal if the user types in ‘dog’ and clicks the submit button?

I’m confused how this works with client side fetch and serverside get.

Any help would be great. Thank you!

Hi there - welcome back to the forums.

Is this in relation to an exercise on Codecademy? If so, can we have the URL to the exercise please?

Generally speaking, one would assume you have something in Express to connect to your database and to which you can provide a SQL query… ?

I figured it out. It was just taking an sqlite3 database from the video tutorial on sqlite3 and manipulating it.

The ?key=value query string caught me up. In the end I understood that req.query.key will provide the value from the query string. Then with sqlite3 we pass in the value from that query string (from an input field), then filter it then grab one piece of the database-which is then sent off to the client side.

1 Like

Just in case anyone has this question. Here is my code, server-side and client side.

//server.js

const express = require(‘express’);

const app = express();

const sqlite3 = require(‘sqlite3’);

const db = new sqlite3.Database(’./acs-1-year-2015.sqlite’);

const morgan = require(‘morgan’);

const bodyParser = require(‘body-parser’);

const path = require(‘path’);

const PORT = 4001;

app.use(bodyParser.json());

app.use(express.json({limit: ‘1mb’}));

app.use(morgan(‘dev’));

app.use(express.static(“public”));

app.get(’/example’, (req, res) =>{

console.log("Got a request!");

console.log(req.query.tutorial);;

const stateName = req.query.tutorial

db.all(`SELECT * FROM states WHERE name =$stateName`, 

    {

        $stateName: stateName

    },

(err, name) => {

    if(err){

        console.log("Take a break");

    } else {

        res.json({name});

    }

})

    //res.json(req.query.tutorial);

})

app.listen(PORT, () => {

console.log(`We are listening on PORT ${PORT}`);

});

//script.js

const btn = document.getElementById(“btn”);

const fetchQuery = async() => {

const inputState = document.getElementById("input").value;

console.log(inputState);

const response = await fetch(`/example?tutorial=${inputState}`);

const data = await response.json();

//console.log(data);

console.log(data.name[0]);

const dataHolder = data.name[0];

const stringer = JSON.stringify(dataHolder);

console.log(stringer);

const root = document.createElement("div");

root.textContent = stringer;

document.body.append(root);

};

btn.addEventListener(“click”, fetchQuery);

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.