因此,可以尝试获取以下JSON对象:

$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=ISO-8859-1
Date: Wed, 30 Oct 2013 22:19:10 GMT
Server: Google Frontend
Cache-Control: private
Alternate-Protocol: 80:quic,80:quic
Transfer-Encoding: chunked

{
   "anotherKey": "anotherValue",
   "key": "value"
}
$

是否有一种方法可以使用node或express在服务器的响应中生成完全相同的正文?显然,我们可以设置报头并指出响应的内容类型将是“application/json”,但是还有不同的方法来编写/发送对象。我所看到的最常用的是使用表单的命令:

response.write(JSON.stringify(anObject));

然而,这有两点,人们可以认为它们是“问题”:

我们正在发送一个字符串。 而且,最后没有新的行字符。

另一个想法是使用命令:

response.send(anObject);

这似乎是在发送一个基于curl输出的JSON对象,类似于上面的第一个示例。但是,当在终端上再次使用curl时,正文末尾没有新的行字符。那么,如何用node或node/express在结尾追加一个新行字符来写出这样的东西呢?


当前回答

如果你试图发送一个json文件,你可以使用流

var fs = require('fs');

var usersFilePath = path.join(__dirname, 'users.min.json');

apiRouter.get('/users', function(req, res){
    var readable = fs.createReadStream(usersFilePath);
    readable.pipe(res);
});

其他回答

旧版本的Express使用app.use(Express .json())或bodyParser.json()阅读更多关于bodyParser中间件的信息

在最新版本的express中,我们可以简单地使用res.json()

const express = require('express'),
    port = process.env.port || 3000,
    app = express()

app.get('/', (req, res) => res.json({key: "value"}))

app.listen(port, () => console.log(`Server start at ${port}`))

您可以使用中间件来设置默认的Content-Type,并为特定的api设置不同的Content-Type。这里有一个例子:

const express = require('express');
const app = express();

const port = process.env.PORT || 3000;

const server = app.listen(port);

server.timeout = 1000 * 60 * 10; // 10 minutes

// Use middleware to set the default Content-Type
app.use(function (req, res, next) {
    res.header('Content-Type', 'application/json');
    next();
});

app.get('/api/endpoint1', (req, res) => {
    res.send(JSON.stringify({value: 1}));
})

app.get('/api/endpoint2', (req, res) => {
    // Set Content-Type differently for this particular API
    res.set({'Content-Type': 'application/xml'});
    res.send(`<note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
        </note>`);
})

以下是解决方案:

//Here, JSON object is doc  
const M={"First Name":doc.First_Name,
          "Last Name":doc.Last_Name,
          "Doctor's Email":doc.Email,
          "Doctors Picture Link":doc.Image};
   res.write(JSON.stringify(M,null,10)+"\n");
   res.end();

其他渲染对象的方法

console.log(doc);
res.json(doc);
//Here,M is referred from the above code it is contains doc Object
res.send(M);

我是如何获得对象使用猫鼬:

//Here, Handles contains my MongoDB Schema.
const NN=Handles.findOne().lean().exec(function(err, doc) {
console.log(doc);
});

对于问题的头部分,我要喊出res。在这里输入:

res.type('json')

等于

res.setHeader('Content-Type', 'application/json')

来源:express docs:

将Content-Type HTTP报头设置为MIME类型,由MIME .lookup()为指定类型确定。如果type包含“/”字符,则它将Content-Type设置为type。

你可以为此创建一个helper:创建一个helper函数,这样你就可以在应用程序的任何地方使用它

function getStandardResponse(status,message,data){
    return {
        status: status,
        message : message,
        data : data
     }
}

这是我的主题路线,我试图得到所有的主题

router.get('/', async (req, res) => {
    const topics = await Topic.find().sort('name');
    return res.json(getStandardResponse(true, "", topics));
});

我们得到的回应

{
"status": true,
"message": "",
"data": [
    {
        "description": "sqswqswqs",
        "timestamp": "2019-11-29T12:46:21.633Z",
        "_id": "5de1131d8f7be5395080f7b9",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031579309.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "sqswqswqs",
        "timestamp": "2019-11-29T12:50:35.627Z",
        "_id": "5de1141bc902041b58377218",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031835605.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": " ",
        "timestamp": "2019-11-30T06:51:18.936Z",
        "_id": "5de211665c3f2c26c00fe64f",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096678917.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "null",
        "timestamp": "2019-11-30T06:51:41.060Z",
        "_id": "5de2117d5c3f2c26c00fe650",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096701051.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "swqdwqd wwwwdwq",
        "timestamp": "2019-11-30T07:05:22.398Z",
        "_id": "5de214b2964be62d78358f87",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575097522372.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "swqdwqd wwwwdwq",
        "timestamp": "2019-11-30T07:36:48.894Z",
        "_id": "5de21c1006f2b81790276f6a",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575099408870.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    }
      ]
}