Thursday, 8 June 2017

Nodejs express posting query via jquery/ajax can't set headers error while reading response

I am trying to read responses from my server after posting a query via jquery and ajax. I think it's because I am trying to render the page using 'res.renderand writing out a response after receiving data from my db usingres.end`. But I don't know how to resolve it as I am a newbie to nodejs express.

Here is my nodejs part that receives the request, queries the db and tries to send the response:

app.all('/Search', function(req, res) {
    res.render('search');
    var query = req.body.username;
    if (req.body.username)
    {
    db.collection('users').find({username: query}).toArray(function(err, result) {
        if (err) return console.log(err);
        console.log("Request body  = "+req.body.username);
        console.log(result);
        res.writeHead(200, { 'Content-Type': 'application/json' }); 
        res.end(JSON.stringify(data));
    });
    }
});

Here is the search.ejs html page with the jquery embedded in it:

<!DOCTYPE html>
<html lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <head>
    <meta charset="UTF-8">
    <title>MY APP</title>
    </head>
    <body>
    <div style="margin: 0 auto;width: 500px;">
        <form id="searchForm" action="/Search" method="post" style="margin: 0 auto; width: 200px; margin-top: 100px;">
        <input id="username" type="text" placeholder="Search" name="username"  style="margin: 20px auto; font-size: 50px;">
        <!-- <input type="file" name="picture"> -->
        <button type="submit"  style="margin: 20px auto; font-size: 50px;">Submit</button>
        </form>
    </div>

    <script type="text/javascript">
     $('#searchForm').on('submit', function (event) {
         console.log("HI");
         event.preventDefault(); // Stop the form from causing a page refresh.
         var data = {
         username: $('#username').val()
         };
         console.log("DATA === "+data);
         $.ajax({
         url: 'http://localhost:3000/Search',
         data: data,
         method: 'POST'
         }).then(function (response) {
         console.log("Response ="+response);
         // Do stuff with the response, like add it to the page dynamically.
             $('body').append(response);
         }).catch(function (err) {
         console.error(err);
         });
     });
    </script>
    </body>
</html>

And here is the output in the terminal:

Server started at port:3000
Request body  = abc
[ { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' } ]
/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb/lib/utils.js:123
    process.nextTick(function() { throw err; });
                                  ^

Error: Can't set headers after they are sent.
    at ServerResponse.setHeader (_http_outgoing.js:371:11)
    at ServerResponse.writeHead (_http_server.js:183:21)
    at /home/vineet/Desktop/serene-brushlands-55292/app.js:52:10
    at handleCallback (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb/lib/utils.js:120:56)
    at /home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb/lib/cursor.js:860:16
    at handleCallback (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:171:5)
    at setCursorDeadAndNotified (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:505:3)
    at nextFunction (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:651:7)
    at Cursor.next [as _next] (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:692:3)
    at fetchDocs (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb/lib/cursor.js:856:10)
    at /home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb/lib/cursor.js:879:7
    at handleCallback (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:171:5)
    at nextFunction (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:682:5)
    at /home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:593:7
    at queryCallback (/home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/cursor.js:232:18)
    at /home/vineet/Desktop/serene-brushlands-55292/node_modules/mongodb-core/lib/connection/pool.js:469:18

The response that I receive in the jquery stub is the html for search.ejs itself. Please help!!



via Vineet Kaushik

No comments:

Post a Comment