Custom response with http-proxy-middleware package












0















In our project we're using the "http-proxy-middleware"(https://www.npmjs.com/package/http-proxy-middleware) npm package for proxy.



There is the "onProxyRes" function to subscribe to http-proxy's event.



And there is an example of that function:



function onProxyRes(proxyRes, req, res) {
proxyRes.headers['x-added'] = 'foobar' // add new header to response
delete proxyRes.headers['x-removed'] // remove header from response
}


I'm just interesting is it possible somehow based on proxyRes write changed response in res object and do not copy data directly from proxyRes object?



Just example:



proxyRes(readable stream contains the following data: {"url": "http://domain/test"}, I'd like to modify that response and have res with data like that: {{"url": "http://changedDomain/test"}} and do not copy data from proxyRes directly










share|improve this question





























    0















    In our project we're using the "http-proxy-middleware"(https://www.npmjs.com/package/http-proxy-middleware) npm package for proxy.



    There is the "onProxyRes" function to subscribe to http-proxy's event.



    And there is an example of that function:



    function onProxyRes(proxyRes, req, res) {
    proxyRes.headers['x-added'] = 'foobar' // add new header to response
    delete proxyRes.headers['x-removed'] // remove header from response
    }


    I'm just interesting is it possible somehow based on proxyRes write changed response in res object and do not copy data directly from proxyRes object?



    Just example:



    proxyRes(readable stream contains the following data: {"url": "http://domain/test"}, I'd like to modify that response and have res with data like that: {{"url": "http://changedDomain/test"}} and do not copy data from proxyRes directly










    share|improve this question



























      0












      0








      0


      1






      In our project we're using the "http-proxy-middleware"(https://www.npmjs.com/package/http-proxy-middleware) npm package for proxy.



      There is the "onProxyRes" function to subscribe to http-proxy's event.



      And there is an example of that function:



      function onProxyRes(proxyRes, req, res) {
      proxyRes.headers['x-added'] = 'foobar' // add new header to response
      delete proxyRes.headers['x-removed'] // remove header from response
      }


      I'm just interesting is it possible somehow based on proxyRes write changed response in res object and do not copy data directly from proxyRes object?



      Just example:



      proxyRes(readable stream contains the following data: {"url": "http://domain/test"}, I'd like to modify that response and have res with data like that: {{"url": "http://changedDomain/test"}} and do not copy data from proxyRes directly










      share|improve this question
















      In our project we're using the "http-proxy-middleware"(https://www.npmjs.com/package/http-proxy-middleware) npm package for proxy.



      There is the "onProxyRes" function to subscribe to http-proxy's event.



      And there is an example of that function:



      function onProxyRes(proxyRes, req, res) {
      proxyRes.headers['x-added'] = 'foobar' // add new header to response
      delete proxyRes.headers['x-removed'] // remove header from response
      }


      I'm just interesting is it possible somehow based on proxyRes write changed response in res object and do not copy data directly from proxyRes object?



      Just example:



      proxyRes(readable stream contains the following data: {"url": "http://domain/test"}, I'd like to modify that response and have res with data like that: {{"url": "http://changedDomain/test"}} and do not copy data from proxyRes directly







      javascript node.js






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 2 at 11:21







      Eugenio R

















      asked Jan 2 at 11:16









      Eugenio REugenio R

      133




      133
























          2 Answers
          2






          active

          oldest

          votes


















          0














          I don't think it's necessary to copy data to res as proxyRes already has changedDomain.
          Here is the set up I implemented:



          const express = require('express');
          const httpProxy = require('http-proxy-middleware');

          const app = express();

          app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

          function onProxyRes (proxyResponse, request, response) {
          console.log('proxyResponse', proxyResponse.headers);
          console.log('response', response.headers);
          }

          // Results
          /*
          proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
          server: 'Apache',
          location: 'http://sometarget.com/api',
          'cache-control': 'max-age=30',
          expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
          'content-length': '231',
          connection: 'close',
          'content-type': 'text/html; charset=iso-8859-1' }
          response undefined
          */


          Everything you'll need will be in proxyRes unless you have a specific use for response...






          share|improve this answer
























          • Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

            – Eugenio R
            Jan 2 at 13:39





















          0














          Maybe it looks ugly little bit, but I'm able to manage that with the following code:



          function onProxyRes(proxyResponse, request, serverResponse) {
          var body = "";
          var _write = serverResponse.write;
          proxyResponse.on('data', function (chunk) {
          body += chunk;
          });

          serverResponse.write = function (data) {
          try{
          var jsonData = JSON.parse(data);
          // here we can modify jsonData
          var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
          _write.call(serverResponse,buf);
          } catch (err) {
          console.log(err);
          }
          }

          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005345%2fcustom-response-with-http-proxy-middleware-package%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I don't think it's necessary to copy data to res as proxyRes already has changedDomain.
            Here is the set up I implemented:



            const express = require('express');
            const httpProxy = require('http-proxy-middleware');

            const app = express();

            app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

            function onProxyRes (proxyResponse, request, response) {
            console.log('proxyResponse', proxyResponse.headers);
            console.log('response', response.headers);
            }

            // Results
            /*
            proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
            server: 'Apache',
            location: 'http://sometarget.com/api',
            'cache-control': 'max-age=30',
            expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
            'content-length': '231',
            connection: 'close',
            'content-type': 'text/html; charset=iso-8859-1' }
            response undefined
            */


            Everything you'll need will be in proxyRes unless you have a specific use for response...






            share|improve this answer
























            • Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

              – Eugenio R
              Jan 2 at 13:39


















            0














            I don't think it's necessary to copy data to res as proxyRes already has changedDomain.
            Here is the set up I implemented:



            const express = require('express');
            const httpProxy = require('http-proxy-middleware');

            const app = express();

            app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

            function onProxyRes (proxyResponse, request, response) {
            console.log('proxyResponse', proxyResponse.headers);
            console.log('response', response.headers);
            }

            // Results
            /*
            proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
            server: 'Apache',
            location: 'http://sometarget.com/api',
            'cache-control': 'max-age=30',
            expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
            'content-length': '231',
            connection: 'close',
            'content-type': 'text/html; charset=iso-8859-1' }
            response undefined
            */


            Everything you'll need will be in proxyRes unless you have a specific use for response...






            share|improve this answer
























            • Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

              – Eugenio R
              Jan 2 at 13:39
















            0












            0








            0







            I don't think it's necessary to copy data to res as proxyRes already has changedDomain.
            Here is the set up I implemented:



            const express = require('express');
            const httpProxy = require('http-proxy-middleware');

            const app = express();

            app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

            function onProxyRes (proxyResponse, request, response) {
            console.log('proxyResponse', proxyResponse.headers);
            console.log('response', response.headers);
            }

            // Results
            /*
            proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
            server: 'Apache',
            location: 'http://sometarget.com/api',
            'cache-control': 'max-age=30',
            expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
            'content-length': '231',
            connection: 'close',
            'content-type': 'text/html; charset=iso-8859-1' }
            response undefined
            */


            Everything you'll need will be in proxyRes unless you have a specific use for response...






            share|improve this answer













            I don't think it's necessary to copy data to res as proxyRes already has changedDomain.
            Here is the set up I implemented:



            const express = require('express');
            const httpProxy = require('http-proxy-middleware');

            const app = express();

            app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

            function onProxyRes (proxyResponse, request, response) {
            console.log('proxyResponse', proxyResponse.headers);
            console.log('response', response.headers);
            }

            // Results
            /*
            proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
            server: 'Apache',
            location: 'http://sometarget.com/api',
            'cache-control': 'max-age=30',
            expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
            'content-length': '231',
            connection: 'close',
            'content-type': 'text/html; charset=iso-8859-1' }
            response undefined
            */


            Everything you'll need will be in proxyRes unless you have a specific use for response...







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 2 at 12:15









            Libby LebyaneLibby Lebyane

            35




            35













            • Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

              – Eugenio R
              Jan 2 at 13:39





















            • Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

              – Eugenio R
              Jan 2 at 13:39



















            Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

            – Eugenio R
            Jan 2 at 13:39







            Thanks for looking into! I asked little bit other thing, actually I'd like to change/modify the server response before sending that to client, like that ticket: github.com/chimurai/http-proxy-middleware/issues/97

            – Eugenio R
            Jan 2 at 13:39















            0














            Maybe it looks ugly little bit, but I'm able to manage that with the following code:



            function onProxyRes(proxyResponse, request, serverResponse) {
            var body = "";
            var _write = serverResponse.write;
            proxyResponse.on('data', function (chunk) {
            body += chunk;
            });

            serverResponse.write = function (data) {
            try{
            var jsonData = JSON.parse(data);
            // here we can modify jsonData
            var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
            _write.call(serverResponse,buf);
            } catch (err) {
            console.log(err);
            }
            }

            }





            share|improve this answer




























              0














              Maybe it looks ugly little bit, but I'm able to manage that with the following code:



              function onProxyRes(proxyResponse, request, serverResponse) {
              var body = "";
              var _write = serverResponse.write;
              proxyResponse.on('data', function (chunk) {
              body += chunk;
              });

              serverResponse.write = function (data) {
              try{
              var jsonData = JSON.parse(data);
              // here we can modify jsonData
              var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
              _write.call(serverResponse,buf);
              } catch (err) {
              console.log(err);
              }
              }

              }





              share|improve this answer


























                0












                0








                0







                Maybe it looks ugly little bit, but I'm able to manage that with the following code:



                function onProxyRes(proxyResponse, request, serverResponse) {
                var body = "";
                var _write = serverResponse.write;
                proxyResponse.on('data', function (chunk) {
                body += chunk;
                });

                serverResponse.write = function (data) {
                try{
                var jsonData = JSON.parse(data);
                // here we can modify jsonData
                var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
                _write.call(serverResponse,buf);
                } catch (err) {
                console.log(err);
                }
                }

                }





                share|improve this answer













                Maybe it looks ugly little bit, but I'm able to manage that with the following code:



                function onProxyRes(proxyResponse, request, serverResponse) {
                var body = "";
                var _write = serverResponse.write;
                proxyResponse.on('data', function (chunk) {
                body += chunk;
                });

                serverResponse.write = function (data) {
                try{
                var jsonData = JSON.parse(data);
                // here we can modify jsonData
                var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
                _write.call(serverResponse,buf);
                } catch (err) {
                console.log(err);
                }
                }

                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 3 at 7:22









                Eugenio REugenio R

                133




                133






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005345%2fcustom-response-with-http-proxy-middleware-package%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith