【问题标题】:Cannot GET the requested API in express.js无法在 express.js 中获取请求的 API
【发布时间】:2018-05-22 16:27:38
【问题描述】:

这是我的快递应用代码

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> 

【问题讨论】:

  • 您的 URL 语法错误 - 尝试 http://&lt;server&gt;:&lt;port&gt;/books?keyword=intro(最后将 / 更改为 ?)。此外,您可能希望隐藏您的服务器 IP。
  • 仅供参考,您永远不应该在服务器上的异步回调中使用if (error) throw error;。对于服务器来说,这绝不是可接受的错误处理。编写实际处理错误的代码 - 可能类似于 console.log(err); res.sendStatus(500); return
  • @Vasan 将 ip 和 / 更改为 ? 但我仍然得到 404
  • @ChristopherBovo 尝试删除路线末尾的/app.get('/books'。另外,您处理 404 的中间件放在哪里?是否放置在所有(有效的)路由中间件之后?
  • @Vasan 我按照你的建议做了,但我仍然得到 404。我目前没有用于 404 错误的中间件

标签: mysql http express get


【解决方案1】:

在httpGetAsync函数中替换

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

与:

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

【讨论】:

  • 这实际上是错误的,因为它会将/books/... 附加到当前完整的 URL(可能在末尾有文件名)。
【解决方案2】:

除非可以接受,否则此答案更像是评论。我想写的声明太长,无法评论。

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

注意? 后面的括号。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-21
    • 2021-12-27
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多