programing

노드 또는 Express를 사용하여 JSON을 반환하는 올바른 방법

nicescript 2023. 2. 15. 23:09
반응형

노드 또는 Express를 사용하여 JSON을 반환하는 올바른 방법

따라서 다음 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"
}
$

노드 또는 express를 사용하여 서버로부터의 응답에 동일한 바디를 작성하는 방법이 있습니까?헤더를 설정하고 응답의 콘텐츠타입이 「애플리케이션/json」이 되는 것을 나타낼 수 있습니다만, 오브젝트를 기입/송신하는 방법은 다릅니다.일반적으로 사용되는 것은 다음 형식의 명령어를 사용하는 것입니다.

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

그러나 이는 마치 '문제'인 것처럼 주장할 수 있는 두 가지 포인트가 있습니다.

  • 스트링을 보냅니다.
  • 게다가, 마지막에 새로운 행은 없습니다.

다음 명령어를 사용하는 방법도 있습니다.

response.send(anObject);

이것은 위의 첫 번째 예시와 유사한 컬의 출력에 기초하여 JSON 객체를 전송하고 있는 것으로 보입니다.단, 단자에서 다시 컬을 사용할 때는 본체 끝에 새로운 라인 문자가 없습니다.그러면 노드 또는 노드/표현을 사용하여 마지막에 새로운 행 문자를 추가한 상태에서 이러한 내용을 실제로 어떻게 적을 수 있을까요?

그 답변도 문자열인데, 만약 당신이 답장을 예쁘게 보내고 싶다면, 뭔가 어색한 이유로, 당신은 이런 것을 사용할 수 있습니다.JSON.stringify(anObject, null, 3)

「정확하게」를 입니다.Content-Type header header header header header header 。application/json 나도 마찬가지야

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

// > {"a":1}

예쁜이:

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);

// >  {
// >     "a": 1
// >  }

회선으로 됩니다.JSON.stringify(...) + '\n'네, 네, 네.

표현

express에서는 옵션을 변경하여 이를 수행할 수 있습니다.

'json replacer'로는 늘)SON(SON)

'json spaces'위한 , 로는 개발2, 입니다.('JSON' 2, '0')

실제로는 40으로 설정하는 것을 권장하지 않습니다.

app.set('json spaces', 40);

그럼 그냥 json으로 응답하면 되겠네

res.json({ a: 1 });

그럼 이렇게 .'json spaces를 설정해 주세요.

Express.js 3x이므로 응답 오브젝트에는 모든 헤더를 올바르게 설정하고 응답을 JSON 형식으로 반환하는 json() 메서드가 있습니다.

예:

res.json({"foo": "bar"});

Express를 사용하는 경우 다음을 사용할 수 있습니다.

res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));

아니면 이것만

res.json({key:"value"});

대부분의 경우 이 기능은 충분합니다.

app.get('/', (req, res) => res.json({ answer: 42 }));

res.json()function은 를 사용하여 JSON에 전달한 파라미터를 변환하고 헤더를 다음과 같이 설정합니다.application/json; charset=utf-8HTTP 클라이언트는 응답을 자동으로 해석하는 방법을 알 수 있습니다.

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

이를 위한 도우미를 만들 수 있습니다.어플리케이션 내 어디에서나 사용할 수 있도록 도우미 기능을 만듭니다.

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
    }
      ]
}

질문의 머리글자 반에 대해서 제가 외칠게요.res.type여기:

res.type('json')

와 동등하다

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

출처: express docs:

Content-Type HTTP 헤더를 지정된 유형의 mime.lookup()에 의해 결정되는 MIME 유형으로 설정합니다.유형에 "/" 문자가 포함되어 있으면 Content-Type을 type으로 설정합니다.

파이프와 여러 프로세서 중 하나를 사용하여 예쁘게 하면 됩니다.앱은 항상 가능한 한 적은 부하로 응답해야 합니다.

$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue | underscore print

https://github.com/ddopson/underscore-cli

미들웨어를 사용하여 기본 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>`);
})

이전 버전의 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}`))

해결책은 다음과 같습니다.

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

Mongoose를 사용하여 오브젝트를 얻는 방법:

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

언급URL : https://stackoverflow.com/questions/19696240/proper-way-to-return-json-using-node-or-express

반응형