Запрос HTTP-заголовка в Node JS - PullRequest
0 голосов
/ 30 апреля 2020

Идея этого приложения в том, что всякий раз, когда вызывается какой-либо URL, он должен давать HTTP-ответ. И я пытаюсь отправить данные в HTTP-заголовок, но я не знаю, как заполнить контент, и не могу найти нигде решения.

Вот мой код

const express = require('express');

let helmet = require('helmet')


const app = express();

app.use(helmet());

app.use((req, response, next) => {
response.writeHead(200, {'Content-Type': 'application/json'});

const link = req.protocol + '://' + req.get('host') + req.originalUrl;
const data = [{ 'text' : 'Meeting Created',
                'attachment' : 
                    {'title':'Board Created', 
                        'text' : 'Visit this URL and share with your participants so that 
                            they can join.',
                        'title_link': link
                    }
                }];


const responseBody = {data};

response.end(JSON.stringify(responseBody))


 });

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

 app.listen(port , () => {
   console.log('Port is listening');
 })

После запуска приложения .. я получаю следующий результат в заголовке

HTTP/1.1 200 OK X-DNS-Prefetch-Control: off X-Frame-Options: SAMEORIGIN Strict-Transport-Security: max-age=15552000; includeSubDomains X-Download-Options: noopen X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Content-Type: application/json Date: Thu, 30 Apr 2020 08:17:05 GMT Connection: keep-alive

Но я хочу дополнительные данные в директивах заголовка HTTP. как показано ниже

Желаемый результат:

{
   "statusCode": 200,
   "content": "{\"text\":\"Meeting Created\",\"attachments\":[{\"title\":\"Join 
    Meeting\",\"text\":\"Visit this URL and share with your meeting participants so that 
    they can join: https://mnow.io/800244\",\"title_link\":\"https://mnow.io/800244\"}]}",
   "headers": {
    "x-dns-prefetch-control": "off",
    "x-frame-options": "SAMEORIGIN",
    "strict-transport-security": "max-age=15552000; includeSubDomains",
    "x-download-options": "noopen",
    "x-content-type-options": "nosniff",
    "x-xss-protection": "1; mode=block",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8",
    "content-length": "216",
    "etag": "W/\"d8-KMGsyQ3ByyfI5IsF7yiwJ86lLWw\"",
    "date": "Tue, 28 Apr 2020 08:11:19 GMT",
    "connection": "close"
  },
  "data": {
  "text": "Meeting Created",
  "attachments": [
  {
    "title": "Join Meeting",
    "text": "Visit this URL and share with your meeting participants so that they can join: 
     http://localhost:4000/",
    "title_link": "http://localhost:4000/"
  }
]
}
}

Ответы [ 2 ]

0 голосов
/ 30 апреля 2020

Используя response.writeHead (). Я получил желаемый результат.

const express = require('express');

    let helmet = require('helmet')


    const app = express();

    app.use(helmet());


    app.use((req, response, next) => {

        const link = req.protocol + '://' + req.get('host') + req.originalUrl;
        const data = [{ 'text' : 'Meeting Created',
                        'attachment' : 
                            {'title':'Board Created', 
                                'text' : 'Visit this URL and share with your participants so that they can join:'+ link,
                                'title_link': link
                            }
                        }];

        const responseBody = {data};


        response.writeHead(200, {'Content-Type': 'application/json; charset=utf-8','data' : JSON.stringify(data)}); // Added This line


        response.end(JSON.stringify(responseBody))


    });


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

    app.listen(port , () => {
        console.log('Port is listening');
    })
0 голосов
/ 30 апреля 2020

Вы можете использовать express ' response.set , чтобы установить заголовок перед отправкой ответа.

Кроме того, если ваш ответ JSON, то вы не не нужно явно устанавливать код состояния или тип содержимого. Простой res.send вызов будет делать. Express позаботится об отдыхе.

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

app.use(helmet());


app.use((req, response) => {

    const link = req.protocol + '://' + req.get('host') + req.originalUrl;
    const data = [{
        'text': 'Meeting Created',
        'attachment':
        {
            'title': 'Board Created',
            'text': 'Visit this URL and share with your participants so that they can join:' + link,
            'title_link': link
        }
    }];

    // You don't need to set content type for JSON response. The headers for that are set automatically by express.
    response.send({ data });
});


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

app.listen(port, () => {
    console.log('Port is listening');
})
...