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

标签 mysql http express get

这是我的 Express 应用程序代码

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

我请求的url是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> 

最佳答案

在httpGetAsync函数中替换

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

与:

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

关于mysql - 无法在express.js中获取请求的API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50472482/

相关文章:

node.js - 如何在 Mongoose 的一个查询中获取数据并进行计数

php - 如何使用 PHP 显示提交的单选按钮值的计数

php - mysql 基于 concat 列表的顺序

java - 我的 JAX-RS 资源服务中的 @FormParam 参数始终为 null

Angular 设置 HTTP 超时

node.js - typescript express 中间件

mysql - 为什么这个 MySQL 语句中的 GROUP BY 子句不抛出错误?

php - 当选择项更改为该选择项新值时更新 mySQL 值

java - 获取 HTTPRequest/HTTPResponse header 大小(以字节为单位)

javascript - ReactJS + MongoDB + NodeJS/ExpressJS : What is process. nextTick(function() { throw err; });?