Код IT
← Каталог

Встроенные модули Node.js — fs, потоки и http — req и res как потоки

Фрагмент из «Встроенные модули Node.js — fs, потоки и http»: req и res как потоки.

javascript javascriptencyclopedia3-ecosystem-1-runtime-node-268 embed URL статья в энциклопедии
JavaScript main.js
import http from 'node:http';

const proxy = http.createServer((clientReq, clientRes) => {
  const options = {
    hostname: 'api.example.com',
    port: 80,
    path: clientReq.url,
    method: clientReq.method,
    headers: clientReq.headers,
  };

  const proxyReq = http.request(options, (proxyRes) => {
    clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
    proxyRes.pipe(clientRes);
  });

  clientReq.pipe(proxyReq);
});
import http from 'node:http';

const proxy = http.createServer((clientReq, clientRes) => {
  const options = {
    hostname: 'api.example.com',
    port: 80,
    path: clientReq.url,
    method: clientReq.method,
    headers: clientReq.headers,
  };

  const proxyReq = http.request(options, (proxyRes) => {
    clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
    proxyRes.pipe(clientRes);
  });

  clientReq.pipe(proxyReq);
});