节点。错误:[错误:需要查询]

时间:2021-07-29 18:33:11

I've been working on a project recently and it requires me to POST the required name to my profile.js file, but when I do console.log(req.body.bookName) (because the data I'm sending is called bookName), it gives me the error of [Error: Query is required]

我最近一直在做一个项目,它要求我把需要的名字贴在我的个人资料上。但当我执行console.log(req.body.bookName)(因为我发送的数据叫做bookName)时,它会给出[error: Query is required]的错误

Here is the post part of my profile.js code

这是我个人资料的一部分。js代码

router.post('/', function(req, res){
if(req.session && req.session.user){
    Book.find({ owner: req.session.user.username || req.session.user }, function(err, book){
        if(err){
            console.log(err);
        }
        books.search(req.body.search, options, function(error, results) {
            if ( ! error ) {
                console.log(req.body.bookName);
                res.render("profile",{
                    authenticated: true,
                    info: books,
                    results: results
                });
            }
            else {
                console.log(error);
            }
        });

    });
}
else{
    res.status(401).send('You must be logged in to access this page');
}
})

Here is my button in my .ejs file

这是我的。ejs文件中的按钮

<form method="POST">
        <input type="text" name="search" placeholder="Search..." required class="searchBook">
        <input type="submit" value="Search">
    </form>
    <% for(var i = 0; i < results.length; i++){ %>
        <div class="ui grid">
            <div class="column four wide">
                <div class="ui card">
                    <div class="image">
                        <img src = "<%= results[i].thumbnail %>"/>
                    </div>
                    <div class="content">
                        <div class="header">
                            <h1 class="ui small header title"><%= results[i].title %></h1>
                        </div>
                        <div class="meta">
                            <p>Author: <%= results[i].authors %></p>
                            <p>Published on: <%= results[i].publishedDate %></p>
                            <p>Pages: <%= results[i].pageCount %></p>
                        </div>
                    </div>
                    <div class="content extra">
                        <button id="detail" class="<%= results[i].title %>">View Detail</button>
                        <button class="ui button fluid" type="button" name="button">Add</button>
                    </div>
                </div>
            </div>
        </div>
        <div id="modaldiv" class="ui modal" style="position: relative">
            <i class="close icon"></i>
            <div class="header"><%=results[i].title%></div>
            <div class="content"><%=results[i].description%></div>
        </div><!-- Should be out side of the book info div -->
    <% } %>

And here is my home.js file where I post my data

这就是我的家。我发布数据的js文件

$(document).ready(() => {
$(document).on("click", "#detail", function () {
    $.ajax({
        type: "POST",
        url: '/profile',
        dataType: 'text',
        data: { bookName: $(this).attr("class")},
        success: function (data) {
            location.reload();
            alert("done");
        }
    });
});
});

Does anyone know why this error happens and how I can solve it?

有人知道为什么会发生这种错误吗?

2 个解决方案

#1


1  

After reading your comment, I found the issue.

读了你的评论后,我发现了问题。

What you send to the server is JSON not text. { bookName: $(this).attr("class")} is JSON not text. Of course, value of bookName is a text, but whole data is JSON.

发送到服务器的是JSON而不是文本。{bookName: $(this).attr("class")}是JSON而不是文本。当然,bookName的值是文本,但整个数据是JSON。

you should

你应该

$.ajax({
        type: "POST",
        url: '/profile',
        contentType: 'application/json',
        data: JSON.stringify({ bookName: $(this).attr("class")}),
        success: function (data) {
            location.reload();
            alert("done");
        }
    });

I believe you attached bodyParser.json() to express. Then, console.log req.body on the '/profile' router. You will see body as JSON.

我相信你附加了bodyparres .json()来表达。然后,控制台。日志请求。在“/profile”路由器上的主体。您将看到body是JSON。

EDIT: one more thing I've found is that you did't send req.body.search It should be something like JSON.stringify({ bookName: $(this).attr("class"), search: $('.searchBook').val() }) That's why you got Error message.

编辑:我还发现你没有发送req.body。搜索应该是JSON。stringify({bookName: $(this).attr(“类”),search: $('. searchbook ').val()},这就是为什么会有错误消息。

EDIT2: You are trying to send form and AJAX simultaneously. It doesn't work like that. Just choose one thing. Form or AJAX. I recommend you to use AJAX. Cancel default behavior of form by using e.preventDefault() in $(document).on('click')

您正在尝试同时发送表单和AJAX。它不是那样工作的。只选择一件事。形式或AJAX。我建议您使用AJAX。通过在$(文档).on('click')中使用e.preventDefault()来取消表单的默认行为。

#2


1  

Look at your query param. You are passing in this line books.search(req.body.search, if you notice, req.body.searchis the query param but search is not defined in the body that you are posting: { bookName: $(this).attr("class")}, only bookname.

查看查询参数。您正在传递这个行。search(req.body)。搜索,如果你注意到了,req.body。searchis查询参数,但是搜索在您发布的主体中没有定义:{bookName: $(这个).attr(“class”)},只有bookName。

I believe you intend to use: books.search(req.body.bookName....

我相信你打算使用:books.search(req.body.bookName ....

Update:

更新:

So I see you have a form that you post with search. The problem is that when that is posted, req.body.search is defined but not req.body.bookName. When then you click #detail, it is a brand new request where search is not being posted. At that point you will need to grab the value of search and post it as part of the same request. As individual request, one contains bookName, the other search but with the code in your current state, they aren't posted together as the nodejs endpoint expects it.

我看到你有一个表单,你发布了搜索。问题是,当它发布时,req.body。搜索是定义的,但不是req.body.bookName。当你点击#detail时,它是一个全新的请求,搜索没有被发布。此时,您需要获取搜索的值并将其作为相同请求的一部分发布。作为单独的请求,其中一个包含bookName,另一个包含搜索,但是使用当前状态的代码,它们不会按照nodejs端点的期望一起发布。

Hope this is of help.

希望这对你有帮助。

#1


1  

After reading your comment, I found the issue.

读了你的评论后,我发现了问题。

What you send to the server is JSON not text. { bookName: $(this).attr("class")} is JSON not text. Of course, value of bookName is a text, but whole data is JSON.

发送到服务器的是JSON而不是文本。{bookName: $(this).attr("class")}是JSON而不是文本。当然,bookName的值是文本,但整个数据是JSON。

you should

你应该

$.ajax({
        type: "POST",
        url: '/profile',
        contentType: 'application/json',
        data: JSON.stringify({ bookName: $(this).attr("class")}),
        success: function (data) {
            location.reload();
            alert("done");
        }
    });

I believe you attached bodyParser.json() to express. Then, console.log req.body on the '/profile' router. You will see body as JSON.

我相信你附加了bodyparres .json()来表达。然后,控制台。日志请求。在“/profile”路由器上的主体。您将看到body是JSON。

EDIT: one more thing I've found is that you did't send req.body.search It should be something like JSON.stringify({ bookName: $(this).attr("class"), search: $('.searchBook').val() }) That's why you got Error message.

编辑:我还发现你没有发送req.body。搜索应该是JSON。stringify({bookName: $(this).attr(“类”),search: $('. searchbook ').val()},这就是为什么会有错误消息。

EDIT2: You are trying to send form and AJAX simultaneously. It doesn't work like that. Just choose one thing. Form or AJAX. I recommend you to use AJAX. Cancel default behavior of form by using e.preventDefault() in $(document).on('click')

您正在尝试同时发送表单和AJAX。它不是那样工作的。只选择一件事。形式或AJAX。我建议您使用AJAX。通过在$(文档).on('click')中使用e.preventDefault()来取消表单的默认行为。

#2


1  

Look at your query param. You are passing in this line books.search(req.body.search, if you notice, req.body.searchis the query param but search is not defined in the body that you are posting: { bookName: $(this).attr("class")}, only bookname.

查看查询参数。您正在传递这个行。search(req.body)。搜索,如果你注意到了,req.body。searchis查询参数,但是搜索在您发布的主体中没有定义:{bookName: $(这个).attr(“class”)},只有bookName。

I believe you intend to use: books.search(req.body.bookName....

我相信你打算使用:books.search(req.body.bookName ....

Update:

更新:

So I see you have a form that you post with search. The problem is that when that is posted, req.body.search is defined but not req.body.bookName. When then you click #detail, it is a brand new request where search is not being posted. At that point you will need to grab the value of search and post it as part of the same request. As individual request, one contains bookName, the other search but with the code in your current state, they aren't posted together as the nodejs endpoint expects it.

我看到你有一个表单,你发布了搜索。问题是,当它发布时,req.body。搜索是定义的,但不是req.body.bookName。当你点击#detail时,它是一个全新的请求,搜索没有被发布。此时,您需要获取搜索的值并将其作为相同请求的一部分发布。作为单独的请求,其中一个包含bookName,另一个包含搜索,但是使用当前状态的代码,它们不会按照nodejs端点的期望一起发布。

Hope this is of help.

希望这对你有帮助。