gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:38:20 31 4
gpt4 key购买 nike

我对 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com