我是后端代码的新手,我正在尝试创建一个函数来响应我的JSON字符串。我现在有一个例子
function random(response) {
console.log("Request handler 'random was called.");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("random numbers that should come in the form of json");
response.end();
}
这基本上只是打印字符串"random numbers that should in the form of JSON“。我想要做的是用一个JSON字符串来响应任何数字。我需要放一个不同的内容类型吗?此函数是否应该将该值传递给客户端的另一个函数?
谢谢你的帮忙!
发布于 2012-03-21 22:03:22
在Express中使用res.json:
function random(response) {
console.log("response.json sets the appropriate header and performs JSON.stringify");
response.json({
anObject: { item1: "item1val", item2: "item2val" },
anArray: ["item1", "item2"],
another: "item"
});
}
或者:
function random(response) {
console.log("Request handler random was called.");
response.writeHead(200, {"Content-Type": "application/json"});
var otherArray = ["item1", "item2"];
var otherObject = { item1: "item1val", item2: "item2val" };
var json = JSON.stringify({
anObject: otherObject,
anArray: otherArray,
another: "item"
});
response.end(json);
}
发布于 2011-05-05 14:38:13
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));
如果你使用alert(JSON.stringify(objToJson))
,你会得到{"response":"value"}
发布于 2013-11-23 23:09:01
在express中,可能存在应用程序范围JSON格式器。
在研究了express\lib\response.js之后,我使用了以下例程:
function writeJsonPToRes(app, req, res, obj) {
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
res.set('Content-Type', 'application/json');
var partOfResponse = JSON.stringify(obj, replacer, spaces)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
var callback = req.query[app.get('jsonp callback name')];
if (callback) {
if (Array.isArray(callback)) callback = callback[0];
res.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
}
res.write(partOfResponse);
}
https://stackoverflow.com/questions/5892569
复制相似问题