无法在express.js中获取所请求的API

问题描述 投票:0回答:2

这是我的快递应用程序代码

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);
            }
        }
    });
});

我要求的网址是http://......../books/keyword=intro。其中intro是用户输入。

我在这里尝试实现的是来自HTML中的输入,获取该信息并将其发送到我的API,因此它可以查询我的数据库并获得我想要的内容。

但我得到404错误,所以我猜我的api配置不正确。

有没有更好的方法来实现我正在做的事情?

keyword=intro甚至是查询我的数据库的正确方法。

我的HTML是这样的

<!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> 

mysql http express get
2个回答
1
投票

在httpGetAsync函数中替换

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

有:

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

0
投票

除非可以接受,否则这个答案更多的是评论。我想写的陈述太长,无法发表评论。

关于我的回答是一个有效的方式来编写你准备好的语句模型?我如何编写我的SQL模型是这样的,它工作正常。您是否从SQL语法中收到任何错误?

请注意?之后的括号。

    selectBooks: function(data, callback) {
        let keyword = "%" + req.query + "%";
        connection.query("SELECT * FROM books WHERE title LIKE ?", [keyword], callback);
    }
© www.soinside.com 2019 - 2024. All rights reserved.