node.js - express怎么拼接json返回?
大家讲道理
大家讲道理 2017-04-17 14:46:58
0
2
851

我用nodejs写服务器,如果我想把我从数据库里查收的对象返回去直接用res.json(doc),但是如果我想在json中加一个字段message:sucess。表示成功怎么写?
就是我想把所有的请求返回的json中都带有message字段这个怎么加?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
大家讲道理

The easiest way:

res.json(JSON.stringify({data: doc, message: success}))

But it will be annoying to write like this all the time. You will gradually optimize your writing

function toJSON (data = {}, message = '', status = '', code = '') {
    return {
        JSON.stringify({ data, message, status, code })
    }
}
左手右手慢动作

res.json supports objects, just write res.json({data, message: 'success'}) like this. If you use strings, it is best to use res.send, res.end, otherwise res.json has to determine the type.

The object returned in this way is

{
    message: 'success',
    data: {} // 原有data.
}

It is recommended to do this, with a layer of packaging. If you add the data field directly to message, if data itself also has a message field, wouldn’t it be overwritten?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template