Christopher Bovo
Christopher Bovo

Reputation: 41

Cannot GET the requested API in express.js

Here is my express app code

app.get('/books',function(req,res){
    var {keyword} =req.query;
    connection.query('SELECT * from books', function (error, results, fields) {
        if (error) throw error;
        for(let result of results){
            if(result.title === keyword){
                res.send(result);
            }
        }
    });
});

and the url i am requesting is http://......../books/keyword=intro. Where intro is the user input.

What i am trying to achieve here, is from an input in HTML, to take that info and send it to my API, so it can query my DB and get what i want.

But i get a 404 error, so i guess my api is configured incorrectly.

Is there a better way to implement what i am doing?

Is the keyword=intro even the correct way to query my db.

My html is like this

<!DOCTYPE html>

</head>




<body>
    <div id="data"> 
        <input type="button" id="button" value="Click"/>
        <input type="text" id="search" >
    </div>
    <div id="search">

    </div>

    <script>
        document.getElementById('button').addEventListener('click',getUserInput);
        function getUserInput(event){
            var userInput = document.getElementById("search").value;
            if(userInput !== ""){
                httpGetAsync(userInput);
            }
        }

        function httpGetAsync(searchTerm){
            var theUrl = 'books?keyword=' + searchTerm;
            const xhttp = new XMLHttpRequest();
            xhttp.open("GET", theUrl, true); // true for asynchronous 
            xhttp.send(null);
            xhttp.onreadystatechange = processRequest;

            function processRequest() {

                if (xhttp.readyState == XMLHttpRequest.DONE);
                var result = JSON.parse(xhttp.response);
                console.log(result);
        }}

    </script>

</body> 

Upvotes: 0

Views: 41

Answers (2)

Curious13
Curious13

Reputation: 329

This answer is more of a comment unless it's acceptable. The statement that I want to write is too long for a comment.

In regards to my answer is that a valid way to write your prepared statement model? How I write my SQL models are like this and it works fine. Are you receiving any errors from your SQL syntax?

Notice the brackets after the ?.

    selectBooks: function(data, callback) {
        let keyword = "%" + req.query + "%";
        connection.query("SELECT * FROM books WHERE title LIKE ?", [keyword], callback);
    }

Upvotes: 0

MCL88
MCL88

Reputation: 11

In httpGetAsync function replace

var theUrl = 'books/keyword=' + searchTerm;

with:

var theUrl = window.location + '/books/keyword=' + searchTerm;

Upvotes: 1

Related Questions