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;
$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
javascript node.js api express.js proxy
$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.
add a comment |
$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
javascript node.js api express.js proxy
$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
add a comment |
$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
javascript node.js api express.js proxy
$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
javascript node.js api express.js proxy
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
add a comment |
$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
add a comment |
1 Answer
1
active
oldest
votes
$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
orCRUD
Keyword.
$endgroup$
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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
orCRUD
Keyword.
$endgroup$
add a comment |
$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
orCRUD
Keyword.
$endgroup$
add a comment |
$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
orCRUD
Keyword.
$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
orCRUD
Keyword.
edited Jan 17 '18 at 21:09
Sᴀᴍ Onᴇᴌᴀ
10.3k62168
10.3k62168
answered Jan 17 '18 at 16:56
copcop
101
101
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
$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