Akhilesh Chobey Akhilesh Chobey - 1 year ago 111
Node.js Question

Express app.get: req.body returns type of value and not the actual value

I am quite novice to Express and working on a project. I have 4 radio buttons which represent user answer. I have stored the correct answers in a MongoLabs database which I retrieve and log in the

function. I want to check the user answer against those correct answers. However when I log
I get
[object Object]


<!DOCTYPE html>
<title>Online Testing Website</title>
<div id="question">
<p>This is my first question</p>
<div id="answer">
<form action="/answer" method="get">
<input id="a" type="radio" name="ans" value="A" >A<br>
<input id="b" type="radio" name="ans" value="B" >B<br>
<input id="c" type="radio" name="ans" value="C" >C<br>
<input id="d" type="radio" name="ans" value="D" >D<br><br><br>
<button type="submit">Submit</button>

<script type="text/javascript" src="./server.js"></script>



const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var path = require('path');
var mongo = require('mongodb').MongoClient;

app.use(bodyParser.urlencoded({extended: true}));

var db;

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');

mongo.connect('mongodb://deodhar:deodhar@ds015636.mlab.com:15636/correct-answers', function (err, database) {
return console.log('mongo connect if: ' + err);
db = database;
app.listen(8080, function () {
console.log("Listening on 8080");

app.get('/answer', function (req,res) {
console.log("User answer: " + req.body);
var cursor = db.collection('answers').find().toArray(function (req,result) {

Answer Source

With GET requests, there won't be a req.body; use req.query instead.

Also, if you want to log the contents of an object, don't use string concatenation (using +), but pass the object as a separate argument to console.log (using ,):

console.log("User answer: ", req.query);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download