理解为什么这不需要JSON.stringify

时间:2015-03-06 10:39:28

标签: javascript json

我对Node.js很新,并且传递了JSON数据,但有人可以让我深入了解为什么我不需要在这里做JSON.stringify。

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'));
        };
    });
};

正如你在底部看到的那样 - res.send(offers)是什么回送但是这会返回有效的JSON数据,但它仍然是一个JavaScript对象?

数据来自couchDB,我拿出我需要的东西,然后把我需要的东西放到offer变量中。

希望你能帮助我理解:)

感谢。

1 个答案:

答案 0 :(得分:1)

node.js响应对象没有send方法,因此我假设您正在使用Express。

来自the documentation

  

当参数是数组或对象时,Express以JSON表示

响应

Restify does the same thing

  

您可以传递代码和正文,也可以传递一个正文。 body可以是Object,Buffer或Error。当你调用send()时,restify会弄清楚如何格式化响应(参见上面的内容协商),并且这样做。

相关问题