Responding with a JSON object in Node.js (converting object/array to JSON string)

前端 未结 6 1094
广开言路
广开言路 2020-12-04 08:01

I\'m a newb to back-end code and I\'m trying to create a function that will respond to me a JSON string. I currently have this from an example

function rando         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 08:54

    in express there may be application-scoped JSON formatters.

    after looking at express\lib\response.js, I'm using this routine:

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

提交回复
热议问题