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

标签 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,我取出我需要的数据,然后将我需要的数据放入 Offers 变量中。

希望你能帮助我理解:)

谢谢。

最佳答案

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

来自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.

关于javascript - 理解为什么这不需要 JSON.stringify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28897035/

相关文章:

javascript - 如何在 dc.js/reductio/crossfilter 中生成滚动标准折线图

json - 使用 InputReader 解析包含数组的 JSON 字符串?

php - Stripe - 通过 PHP、iOS 和 Alamofire 进行部分退款

javascript - NodeJS/JS 如何通过 sha256 正确散列对象 json 和字符串(串联)

javascript - 组内的动态 CSS 选择、SVG、路径

javascript - 来自 json 的 Angular JS 中的动态表

javascript - ng-submit angular js不能在php中工作

javascript - 使用来自 Processing-JS 的 JSON

json - 了解 REST 响应和 HTTP 状态码

javascript - 期望 JSON 输出不会在 node.js 输出中返回