0

I'm fairly new to Node.js and passing around JSON data, however can someone please give me an insight into why I don't need to do JSON.stringify in this.

module.exports.getBusinessOffers = function(req, res, next) {
    var business = req.params.businessname;
    console.log('Get All OFFERS from' + business);
    //Gets all offers from couchDB as JSON
    var url = 'http://localhost:5984/offers/_design/offers/_view/business?startkey="' + business + '"&endkey="' + business + '"';
    request.get(url, function(err, response, body) {
        if(err) {
            return next(new restify.InternalServerError('Error communicating with CouchDB'));
        }
        if(response.statusCode === 200) {
            var resp = JSON.parse(body);
            var allOffers = [];
            resp.rows.forEach(function(i) {
                var offer = {
                    title: i.value.offer_title,
                    description: i.value.offer_description,
                    businessname: i.value.businessname,
                    last_modified: i.value.last_modified
                };
                allOffers.push(offer);
            });
            var offers = {
                total_Offers: resp.rows.length,
                offers: allOffers
            };
            res.send(offers);
        } else if(response.statusCode === 404) {
            return next(new restify.InternalServerError('No Offers Found'));
        };
    });
};

As you can see at the bottom - res.send(offers) is whats sent back however this returns valid JSON data but it's still a JavaScript object?

The data is coming from couchDB and I pluck out what I need and then place what I need into the offers variable.

Hope you can help me understand :)

Thanks.

0

1 Answer 1

1

The node.js response object doesn't have a send method so I'm assuming you are using Express.

From the documentation:

When the parameter is an Array or Object, Express responds with the JSON representation

Restify does the same thing:

You can pass send either a code and body, or just a body. body can be an Object, a Buffer, or an Error. When you call send(), restify figures out how to format the response (see content-negotiation, above), and does that.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh sorry I forgot to add - I am using restify.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.