这是我的 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/