【发布时间】: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://<server>:<port>/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 错误的中间件