Ievgen
Ievgen

Reputation: 4443

Node.js express send raw HTTP responses

I have a legacy system that can return raw\plain HTTP responses as a string (text that contains all the required headers + body).

I would like to send this text directly without any parsing modifications for performance reasons.

So goal is to proxy received raw HTTP response.

const express = require('express');
const app = express();
const router = app.Router();

        router.get('request',()=>{
           const plainTextWithHeadersFromExternalSystem = `HTTP/1.1 200 OK
                                   Date: Sun, 10 Oct 2010 23:26:07 GMT
                                   Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 
                                   OpenSSL/0.9.8g
                                   Last-Modified: Sun, 26 Sep 2010 22:04:35 GMT
                                   ETag: "45b6-834-49130cc1182c0"
                                   Accept-Ranges: bytes
                                   Content-Length: 12
                                   Connection: close
                                   Content-Type: text/html

                                   Hello world!`;
           ... TODO: send text with headers and body as a response.
        });

It can be any content type, not only a plain text.

Any ideas whether it's possible to simply proxy it with the Node.js express lib?

Upvotes: 3

Views: 4725

Answers (3)

thebearingedge
thebearingedge

Reputation: 681

I had the same problem myself and had to dive deeper into Node's core http and net modules to figure it out.

To skip the default HTTP response line (e.g. HTTP/1.1 200 OK) and all of the headers that Express/Node.js send, you can send your text directly through the response's socket.

const responseMessage = `HTTP/1.1 200 OK
Date: Sun, 10 Oct 2010 23:26:07 GMT
Content-Type: text/html
Content-Length: 13

Hello, World!

`

router.get('/request', (req, res) => {
  res.socket.end(responseMessage)
})

Upvotes: 4

Rohit Ambre
Rohit Ambre

Reputation: 961

you can use following to set headers

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  // extra headers here
})

or you use
res.header(field, [value])

complete code can be like this

router.get('request', (req, res) => {
   res.set({
      'Content-Type': 'text/plain',
      'Content-Length': '123',
      // extra headers here
   });
   res.send('Hello world!');
});

Upvotes: 1

Józef Podlecki
Józef Podlecki

Reputation: 11283

I think if you set type to text/plain and put string in send you can get exactly what you need

router.get('request', (req, res) => {
  res.type('text/plain');
  res.send('text');
})

Upvotes: 2

Related Questions