SoFunction
Updated on 2025-04-12

Sample code for Koa proxy Http requests

Koa proxy http requests to solve cross-domain problems

1. Why use Koa as a cross-domain proxy?

"Initially, in order to solve the cross-domain problem, I deployed the site to nginx and solved the problem. During an occasional interview opportunity, the interviewer proposed a hypothesis that I needed to adapt the data returned by the submitted API and the API, so will nginx not be satisfied? Of course, the question asked me to consider that if I set up a site myself, forward it through this site, and adapt to the request and response of third-party APIs, it would be better to set up a site. Then there are actually many languages ​​for setting up a site, such as .net, java, nodejs, php..., why choose nodejs in the end? The most important reason for me is the lightweight and JavaScript language affinity of nodejs.

2. Build nodejs application

Since Koa2 has just been released, after all, learn technology, so learn the latest one.

Since you are building a program, start from the program entrance and write the program route first.

const fs = require('fs')
const Router = require('koa-router');
const {httpHandle} = require('../Infrastructure/httpHandle');
const koaBody = require('koa-body')({
  multipart :true
});

const render = (page) => {
  return new Promise((resolve, reject) => {
    let viewUrl = `./view/${page}`
    (viewUrl, "binary", (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

let api = new Router();

('*', httpHandle)
  .post('*', koaBody, httpHandle)
  .put('*', koaBody, httpHandle).del('*', koaBody, httpHandle);

let common = new Router();
('*', async (ctx) => {
   = await render('');
})

let router = new Router();
('/api', (), ());
('/', (), ());
 = router;

The second is to handle the proxy request

const httpRequest = (ctx) => {
  return new Promise((resolve) => {
    delete ;
    const options = {
      host,
      port,
      path: (4, ),
      method: ,
      headers: 
    }
    let requestBody='',
      body,
      head,
      chunks = [],
      fileFields,
      files,
      boundaryKey,
      boundary,
      endData,
      filesLength,
      totallength = 0;

    if () {
      (['content-type'])
      if (['content-type'].indexOf('application/x-www-form-urlencoded') > -1) {
        requestBody = ();
        ['Content-Length'] = (requestBody)
      } else if (['content-type'].indexOf('application/json') > -1) {
        requestBody = ();
        ['Content-Length'] = (requestBody)
      } else if (['content-type'].indexOf('multipart/form-data') > -1) {
        fileFields = ;
        files = ;
        boundaryKey = ().toString(16);
        boundary = `\r\n----${boundaryKey}\r\n`;
        endData = `\r\n----${boundaryKey}--`;
        filesLength = 0;

        (fileFields).forEach((key) => {
          requestBody += `${boundary}Content-Disposition:form-data;name="${key}"\r\n\r\n${fileFields[key]}`;
        })

        (files).forEach((key) => {
          requestBody += `${boundary}Content-Type: application/octet-stream\r\nContent-Disposition: form-data; name="${key}";filename="${files[key].name}"\r\nContent-Transfer-Encoding: binary\r\n\r\n`;
          filesLength += (requestBody,'utf-8') + files[key].size;
        })

        ['Content-Type'] = `multipart/form-data; boundary=--${boundaryKey}`;
        [`Content-Length`] = filesLength + (endData);
      } else {
        requestBody = ()
        ['Content-Length'] = (requestBody)
      }
    }

    const req = (options, (res) => {
      ('data', (chunk) => {
        (chunk);
        totallength += ;
      })

      ('end', () => {
        body = (chunks, totallength);
        head = ;
        resolve({head, body});
      })
    })

     && (requestBody);

    if (fileFields) {
      let filesArr = (files);
      let uploadConnt = 0;
      ((key) => {
        let fileStream = (files[key].path);
        ('end', () => {
          (files[key].path);
          uploadConnt++;
          if (uploadConnt == ) {
            (endData)
          }
        })
        (req, {end: false})
      })
    } else {
      ();
    }

  })
}

This simple line of code implements cross-domain request proxying through nodejs.github link

nginx proxy config configuration is as follows

server {
   listen     1024; 
   server_name   tigrex:1024;
   root      home/TuoTuo.;
   index      ;
   access_log   logs/;
   error_log    logs/;

   charset     utf-8;
   
   location /api {
     proxy_pass  http://127.0.0.1:1023/;
     proxy_set_header Host $host;
     proxy_redirect off;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   }  
   
   location / {
     try_files $uri $uri/ /;     
    }
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.