Node.js/Express middleware to relay requests to various APIs The 2019 Stack Overflow Developer Survey Results Are In Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar ManaraExporting routes in node.js Express 4Reading content of directory for each HTTP requestRestructure of Express CORS middleware for unit test“RESTful” node.js server using expressSpring Boot RESTful service as a backend and reactjs as frontend appValidating list of values to be sent to APIAvoid existSync function on Node.js - Express API controllerMini Tor implementation (“CLI only anonymous network”)ACL express middleware implementation

Can each chord in a progression create its own key?

Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?

Do warforged have souls?

Simulating Exploding Dice

Button changing its text & action. Good or terrible?

How do you keep chess fun when your opponent constantly beats you?

What is the padding with red substance inside of steak packaging?

ELI5: Why do they say that Israel would have been the fourth country to land a spacecraft on the Moon and why do they call it low cost?

What other Star Trek series did the main TNG cast show up in?

What is the role of 'For' here?

How do I design a circuit to convert a 100 mV and 50 Hz sine wave to a square wave?

Does Parliament hold absolute power in the UK?

Why are PDP-7-style microprogrammed instructions out of vogue?

Does Parliament need to approve the new Brexit delay to 31 October 2019?

What information about me do stores get via my credit card?

Didn't get enough time to take a Coding Test - what to do now?

Presidential Pardon

"... to apply for a visa" or "... and applied for a visa"?

Python - Fishing Simulator

What can I do if neighbor is blocking my solar panels intentionally?

Was credit for the black hole image misappropriated?

"is" operation returns false with ndarray.data attribute, even though two array objects have same id

How to handle characters who are more educated than the author?

Why can't wing-mounted spoilers be used to steepen approaches?



Node.js/Express middleware to relay requests to various APIs



The 2019 Stack Overflow Developer Survey Results Are In
Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar ManaraExporting routes in node.js Express 4Reading content of directory for each HTTP requestRestructure of Express CORS middleware for unit test“RESTful” node.js server using expressSpring Boot RESTful service as a backend and reactjs as frontend appValidating list of values to be sent to APIAvoid existSync function on Node.js - Express API controllerMini Tor implementation (“CLI only anonymous network”)ACL express middleware implementation



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I am creating a nodejs middleware server that will handle api transactions from a frontend and relay them to various api's (internal and external). The primary goal is to hide api keys from the frontend. It can also consolidate requests that may require 2 or more endpoints, and modify data structures, thus simplifying our frontend code.



I am hoping for feedback on overall design/structure which will allow us to create a project that will be flexible as we add more apis while keeping it DRY



URLs, keys, etc. are stored in a .env file



index.js



require('dotenv').load();
const express = require('express'),
app = express(),
request = require("./request").request,
bodyParser = require('body-parser');

app.use(bodyParser.json());

//returns all locations
app.get("/locations", (req, res) =>
let URL = '...';
request(
method: 'get',
url: URL,
api: 'apiName'
).then((resp) =>
res.json(resp);
)
);

//send password reset link
app.post("/resetemail", (req, res) =>
let URL = '...';
let DATA = req.body;

request(
method: 'post',
url: URL,
api: 'apiName',
data: DATA
).then((resp) =>
res.json(resp);
)
);

app.listen(3000);


request.js



module.exports.request = function (options) 

const client = require('./' + options.api).instance;
const handleError = require('./' + options.api).handleError;
const onSuccess = function (response)
console.log('Request Successful!', response);
return response.data;


return client(options)
.then(onSuccess)
.catch(handleError);



apiName.js



const axios = require('axios');
const axiosInstance = axios.create(
headers: "token": process.env.API_TOKEN ,
baseURL: process.env.API_BASE_URL,
timeout: 2000
);

const handleError = function (error) error.message);


module.exports =
instance: axiosInstance,
handleError: handleError










share|improve this question











$endgroup$




bumped to the homepage by Community 3 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • $begingroup$
    Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients?
    $endgroup$
    – ferada
    Jan 16 '18 at 21:31






  • 2




    $begingroup$
    Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense?
    $endgroup$
    – jriggs
    Jan 16 '18 at 22:04










  • $begingroup$
    "It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 22 '18 at 20:24

















2












$begingroup$


I am creating a nodejs middleware server that will handle api transactions from a frontend and relay them to various api's (internal and external). The primary goal is to hide api keys from the frontend. It can also consolidate requests that may require 2 or more endpoints, and modify data structures, thus simplifying our frontend code.



I am hoping for feedback on overall design/structure which will allow us to create a project that will be flexible as we add more apis while keeping it DRY



URLs, keys, etc. are stored in a .env file



index.js



require('dotenv').load();
const express = require('express'),
app = express(),
request = require("./request").request,
bodyParser = require('body-parser');

app.use(bodyParser.json());

//returns all locations
app.get("/locations", (req, res) =>
let URL = '...';
request(
method: 'get',
url: URL,
api: 'apiName'
).then((resp) =>
res.json(resp);
)
);

//send password reset link
app.post("/resetemail", (req, res) =>
let URL = '...';
let DATA = req.body;

request(
method: 'post',
url: URL,
api: 'apiName',
data: DATA
).then((resp) =>
res.json(resp);
)
);

app.listen(3000);


request.js



module.exports.request = function (options) 

const client = require('./' + options.api).instance;
const handleError = require('./' + options.api).handleError;
const onSuccess = function (response)
console.log('Request Successful!', response);
return response.data;


return client(options)
.then(onSuccess)
.catch(handleError);



apiName.js



const axios = require('axios');
const axiosInstance = axios.create(
headers: "token": process.env.API_TOKEN ,
baseURL: process.env.API_BASE_URL,
timeout: 2000
);

const handleError = function (error) error.message);


module.exports =
instance: axiosInstance,
handleError: handleError










share|improve this question











$endgroup$




bumped to the homepage by Community 3 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • $begingroup$
    Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients?
    $endgroup$
    – ferada
    Jan 16 '18 at 21:31






  • 2




    $begingroup$
    Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense?
    $endgroup$
    – jriggs
    Jan 16 '18 at 22:04










  • $begingroup$
    "It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 22 '18 at 20:24













2












2








2





$begingroup$


I am creating a nodejs middleware server that will handle api transactions from a frontend and relay them to various api's (internal and external). The primary goal is to hide api keys from the frontend. It can also consolidate requests that may require 2 or more endpoints, and modify data structures, thus simplifying our frontend code.



I am hoping for feedback on overall design/structure which will allow us to create a project that will be flexible as we add more apis while keeping it DRY



URLs, keys, etc. are stored in a .env file



index.js



require('dotenv').load();
const express = require('express'),
app = express(),
request = require("./request").request,
bodyParser = require('body-parser');

app.use(bodyParser.json());

//returns all locations
app.get("/locations", (req, res) =>
let URL = '...';
request(
method: 'get',
url: URL,
api: 'apiName'
).then((resp) =>
res.json(resp);
)
);

//send password reset link
app.post("/resetemail", (req, res) =>
let URL = '...';
let DATA = req.body;

request(
method: 'post',
url: URL,
api: 'apiName',
data: DATA
).then((resp) =>
res.json(resp);
)
);

app.listen(3000);


request.js



module.exports.request = function (options) 

const client = require('./' + options.api).instance;
const handleError = require('./' + options.api).handleError;
const onSuccess = function (response)
console.log('Request Successful!', response);
return response.data;


return client(options)
.then(onSuccess)
.catch(handleError);



apiName.js



const axios = require('axios');
const axiosInstance = axios.create(
headers: "token": process.env.API_TOKEN ,
baseURL: process.env.API_BASE_URL,
timeout: 2000
);

const handleError = function (error) error.message);


module.exports =
instance: axiosInstance,
handleError: handleError










share|improve this question











$endgroup$




I am creating a nodejs middleware server that will handle api transactions from a frontend and relay them to various api's (internal and external). The primary goal is to hide api keys from the frontend. It can also consolidate requests that may require 2 or more endpoints, and modify data structures, thus simplifying our frontend code.



I am hoping for feedback on overall design/structure which will allow us to create a project that will be flexible as we add more apis while keeping it DRY



URLs, keys, etc. are stored in a .env file



index.js



require('dotenv').load();
const express = require('express'),
app = express(),
request = require("./request").request,
bodyParser = require('body-parser');

app.use(bodyParser.json());

//returns all locations
app.get("/locations", (req, res) =>
let URL = '...';
request(
method: 'get',
url: URL,
api: 'apiName'
).then((resp) =>
res.json(resp);
)
);

//send password reset link
app.post("/resetemail", (req, res) =>
let URL = '...';
let DATA = req.body;

request(
method: 'post',
url: URL,
api: 'apiName',
data: DATA
).then((resp) =>
res.json(resp);
)
);

app.listen(3000);


request.js



module.exports.request = function (options) 

const client = require('./' + options.api).instance;
const handleError = require('./' + options.api).handleError;
const onSuccess = function (response)
console.log('Request Successful!', response);
return response.data;


return client(options)
.then(onSuccess)
.catch(handleError);



apiName.js



const axios = require('axios');
const axiosInstance = axios.create(
headers: "token": process.env.API_TOKEN ,
baseURL: process.env.API_BASE_URL,
timeout: 2000
);

const handleError = function (error) error.message);


module.exports =
instance: axiosInstance,
handleError: handleError







javascript node.js api express.js proxy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 12 '18 at 22:08









200_success

131k17157422




131k17157422










asked Jan 12 '18 at 21:47









jriggsjriggs

286




286





bumped to the homepage by Community 3 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 3 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.













  • $begingroup$
    Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients?
    $endgroup$
    – ferada
    Jan 16 '18 at 21:31






  • 2




    $begingroup$
    Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense?
    $endgroup$
    – jriggs
    Jan 16 '18 at 22:04










  • $begingroup$
    "It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 22 '18 at 20:24
















  • $begingroup$
    Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients?
    $endgroup$
    – ferada
    Jan 16 '18 at 21:31






  • 2




    $begingroup$
    Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense?
    $endgroup$
    – jriggs
    Jan 16 '18 at 22:04










  • $begingroup$
    "It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 22 '18 at 20:24















$begingroup$
Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients?
$endgroup$
– ferada
Jan 16 '18 at 21:31




$begingroup$
Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients?
$endgroup$
– ferada
Jan 16 '18 at 21:31




2




2




$begingroup$
Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense?
$endgroup$
– jriggs
Jan 16 '18 at 22:04




$begingroup$
Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense?
$endgroup$
– jriggs
Jan 16 '18 at 22:04












$begingroup$
"It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code?
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
Jan 22 '18 at 20:24




$begingroup$
"It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code?
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
Jan 22 '18 at 20:24










1 Answer
1






active

oldest

votes


















0












$begingroup$

I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.



I would suggest the NPM Module express-app-generator



The advantages of it include:



  • Code Management in clean way.

  • Structured Routing.

  • Add Multiple Middle-Wares in filters array.

  • Create CRUD API's with REST or CRUD Keyword.





share|improve this answer











$endgroup$













    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: "196"
    ;
    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: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2fcodereview.stackexchange.com%2fquestions%2f184991%2fnode-js-express-middleware-to-relay-requests-to-various-apis%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0












    $begingroup$

    I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.



    I would suggest the NPM Module express-app-generator



    The advantages of it include:



    • Code Management in clean way.

    • Structured Routing.

    • Add Multiple Middle-Wares in filters array.

    • Create CRUD API's with REST or CRUD Keyword.





    share|improve this answer











    $endgroup$

















      0












      $begingroup$

      I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.



      I would suggest the NPM Module express-app-generator



      The advantages of it include:



      • Code Management in clean way.

      • Structured Routing.

      • Add Multiple Middle-Wares in filters array.

      • Create CRUD API's with REST or CRUD Keyword.





      share|improve this answer











      $endgroup$















        0












        0








        0





        $begingroup$

        I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.



        I would suggest the NPM Module express-app-generator



        The advantages of it include:



        • Code Management in clean way.

        • Structured Routing.

        • Add Multiple Middle-Wares in filters array.

        • Create CRUD API's with REST or CRUD Keyword.





        share|improve this answer











        $endgroup$



        I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.



        I would suggest the NPM Module express-app-generator



        The advantages of it include:



        • Code Management in clean way.

        • Structured Routing.

        • Add Multiple Middle-Wares in filters array.

        • Create CRUD API's with REST or CRUD Keyword.






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 17 '18 at 21:09









        Sᴀᴍ Onᴇᴌᴀ

        10.3k62168




        10.3k62168










        answered Jan 17 '18 at 16:56









        copcop

        101




        101



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • 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.

            Use MathJax to format equations. MathJax reference.


            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%2fcodereview.stackexchange.com%2fquestions%2f184991%2fnode-js-express-middleware-to-relay-requests-to-various-apis%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

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar