user3335607 user3335607 - 2 months ago 13
Javascript Question

POST request returning [Object, object]

I am trying to send a POST request (using postman) to create an entry in my PostgreSQL database. However, currently my POST request is returning [object, Object], and I cannot figure out why.

Here is the code to handle the request.

//enable the router
app.use('/', router);

//Create
router.post('/api/v1/todos', (req, res, next) => {
const results = [];
console.log("Congrats you hit the create function!!");

//grab data from http-request, 'complete' is from a boolean value in the database
const data = {text: req.query.text, complete: false };

//give error if not recieving a request
if(!req.query.text) res.send(400, "The Request data is: " + req.query);

//get a prostgres client from the connection pool
pg.connect(connectionString, (err, client, done) => {
//handle connection errors
if (err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}

//SQL Query -> Insert Data
client.query('INSERT INTO items(text, complete) values($1,$2)',
[data.text, data.complete]);

//SQL Query -> Select Data
const query = client.query("SELECT * FROM items ORDER BY id ASC");

//Stream results back one row at a time
query.on('row', (row) => {
results.push(row);
});

//After all data is returned, close connection and return the results
query.on('end', () => {
done();
return res.json(results);
//return res.json(data);
});
});
});


And here is my POST
POST image

Why is my data returning objects? What can I do in order to resolve this?

Here is my full code.

Answer

You're concatenating a string with an object, this will convert the object to a string in a form of [object Object].

Here's your problem: if(!req.query.text) res.send(400, "The Request data is: " + req.query);

req.query is an object (you're just checking it the text property exists) and you're concatenating a string to that object.

Comments